var express = require('express');
var router = express.Router();
const aiimg = require('../db/aiimg')
const multer = require('multer')
const path = require('path')
const fs = require('fs')
// 引入Ollama AI客户端
const { analyzeWithOllama, checkOllamaStatus } = require('../utils/ollamaClient')
// 面部分析相关依赖将在后续添加
const faceapi = require('face-api.js')
const { createCanvas, loadImage } = require('canvas')
// 配置 face-api.js 使用 canvas
const { Canvas, Image, ImageData } = require('canvas')
faceapi.env.monkeyPatch({ Canvas, Image, ImageData })

// 轻量日志开关（默认精简，仅在设置 DEBUG_FACE_ANALYSIS=1 时打印详细日志）
const DEBUG_FACE_ANALYSIS = String(process.env.DEBUG_FACE_ANALYSIS || '').toLowerCase() === '1' || String(process.env.DEBUG_FACE_ANALYSIS || '').toLowerCase() === 'true'
const __ORIGINAL_CONSOLE_LOG = console.log.bind(console)
console.log = (...args) => {
  try {
    const firstArg = args[0]
    const isString = typeof firstArg === 'string'
    const isWarningOrError = isString && (firstArg.startsWith('⚠️') || firstArg.startsWith('❌'))
    const keepKeywords = [
      '🚀 开始初始化face-api.js',
      '✅ face-api.js 模型加载完成',
      '🎯 系统准备就绪',
      '🤖 检查Ollama AI服务状态',
      '🔍 开始分析图片',
      '✅ 面部分析完成',
      '📊 分析结果:',
      '🎯 最终结果汇总',
      '🏆 黄金比例综合评分'
    ]
    const isImportant = isString && keepKeywords.some(k => firstArg.includes(k))
    if (DEBUG_FACE_ANALYSIS || isWarningOrError || isImportant) {
      __ORIGINAL_CONSOLE_LOG(...args)
    }
  } catch (e) {
    __ORIGINAL_CONSOLE_LOG(...args)
  }
}

// 初始化状态
let isModelLoaded = false

// 直接加载face-api.js模型（它内置了TensorFlow.js）
console.log('🚀 开始初始化face-api.js...')
loadFaceApiModels()

// 加载face-api.js模型
async function loadFaceApiModels() {
  try {
    console.log('🔄 开始加载face-api.js模型...')
    const modelPath = path.join(__dirname, '../models')
    
    await Promise.all([
      faceapi.nets.tinyFaceDetector.loadFromDisk(modelPath),
      faceapi.nets.faceLandmark68Net.loadFromDisk(modelPath),
      faceapi.nets.faceExpressionNet.loadFromDisk(modelPath),
      faceapi.nets.ageGenderNet.loadFromDisk(modelPath)  // 添加年龄性别检测模型
    ])
    
    isModelLoaded = true
    console.log('✅ face-api.js 模型加载完成')
    console.log('🎯 系统准备就绪，可以处理面部分析请求')
    
    // 检查Ollama AI服务状态
    console.log('🤖 检查Ollama AI服务状态...')
    checkOllamaStatus()
  } catch (error) {
    console.error('❌ face-api.js 模型加载失败:', error)
    console.log('💡 提示：请确保 models 目录下有正确的模型文件')
    console.log('💡 需要包含以下模型文件:')
    console.log('   - tiny_face_detector_model-shard1')
    console.log('   - face_landmark_68_model-shard1')
    console.log('   - face_expression_model-shard1')
    console.log('   - age_gender_model-shard1')
  }
}

// 检查系统是否准备就绪
function isSystemReady() {
  return isModelLoaded
}

// 全局数据统计
global.faceShapeStats = global.faceShapeStats || {
  samples: [],
  count: 0
}

// 添加样本数据
function addFaceShapeSample(data) {
  global.faceShapeStats.samples.push(data)
  global.faceShapeStats.count++
  
  // 保留最近50个样本
  if (global.faceShapeStats.samples.length > 50) {
    global.faceShapeStats.samples.shift()
  }
  
  // 每10个样本分析一次
  if (global.faceShapeStats.count % 10 === 0) {
    analyzeFaceShapeDistribution()
  }
}

// 分析脸型分布并建议调整
function analyzeFaceShapeDistribution() {
  const samples = global.faceShapeStats.samples
  if (samples.length < 5) return
  
  // 统计各脸型数量
  const shapeCount = {}
  const ratioStats = {
    faceRatio: [],
    jawRatio: [],
    cheekRatio: [],
    foreheadRatio: []
  }
  
  samples.forEach(sample => {
    shapeCount[sample.result] = (shapeCount[sample.result] || 0) + 1
    ratioStats.faceRatio.push(sample.faceRatio)
    ratioStats.jawRatio.push(sample.jawRatio)
    ratioStats.cheekRatio.push(sample.cheekRatio)
    ratioStats.foreheadRatio.push(sample.foreheadRatio)
  })
  
  
  // 计算平均值和建议阈值
  const avgFaceRatio = ratioStats.faceRatio.reduce((a, b) => a + b, 0) / ratioStats.faceRatio.length
  const avgJawRatio = ratioStats.jawRatio.reduce((a, b) => a + b, 0) / ratioStats.jawRatio.length
  const avgCheekRatio = ratioStats.cheekRatio.reduce((a, b) => a + b, 0) / ratioStats.cheekRatio.length
  const avgForeheadRatio = ratioStats.foreheadRatio.reduce((a, b) => a + b, 0) / ratioStats.foreheadRatio.length
  
  
  const roundPercentage = (shapeCount['round'] || 0) / samples.length
  if (roundPercentage > 0.6) {
    console.log('⚠️ 圆脸比例过高，建议调整算法阈值')
  }
}

// 表情翻译映射
const expressionTranslations = {
  // 基本表情
  'happy': '开心',
  'sad': '悲伤',
  'angry': '愤怒',
  'surprised': '惊讶',
  'fear': '恐惧',
  'disgust': '厌恶',
  'neutral': '平静',
  
  // 扩展表情
  'joy': '喜悦',
  'excitement': '兴奋',
  'contempt': '轻蔑',
  'confusion': '困惑',
  'disappointment': '失望',
  'embarrassment': '尴尬',
  'pride': '自豪',
  'shame': '羞愧',
  'relief': '放松',
  'anxiety': '焦虑',
  'boredom': '无聊',
  'curiosity': '好奇',
  'determination': '坚定',
  'satisfaction': '满意',
  'frustration': '沮丧',
  'optimism': '乐观',
  'pessimism': '悲观',
  'serenity': '宁静',
  'melancholy': '忧郁',
  'enthusiasm': '热情',
  
  // 微表情
  'smile': '微笑',
  'frown': '皱眉',
  'smirk': '得意',
  'pout': '撅嘴',
  'grin': '咧嘴笑',
  'scowl': '怒容',
  'wink': '眨眼',
  'laugh': '大笑',
  'cry': '哭泣',
  'yawn': '打哈欠',
  
  // 复合表情
  'happy_surprised': '惊喜',
  'sad_angry': '愤懑',
  'calm_confident': '淡定自信',
  'nervous_excited': '紧张兴奋',
  'tired_content': '疲惫满足'
};

// 表情翻译函数
function translateExpression(expression) {
  if (!expression) return '未知';
  
  // 转换为小写进行匹配
  const lowerExpression = expression.toLowerCase().trim();
  
  // 直接匹配
  if (expressionTranslations[lowerExpression]) {
    return expressionTranslations[lowerExpression];
  }
  
  // 模糊匹配（处理复合词）
  for (const [key, value] of Object.entries(expressionTranslations)) {
    if (lowerExpression.includes(key) || key.includes(lowerExpression)) {
      return value;
    }
  }
  
  // 如果没有找到匹配，返回原文（首字母大写）
  return expression.charAt(0).toUpperCase() + expression.slice(1);
}

// 通用分析结果翻译函数 - 确保所有分析文本都是中文
function translateAnalysisText(text) {
  if (!text || typeof text !== 'string') return text;
  
  // 完整的英文分析结果翻译映射
  const analysisTranslations = {
    // 黄金比例相关
    'perfect golden ratio': '完美黄金比例',
    'excellent golden ratio': '极佳黄金比例', 
    'good golden ratio': '良好黄金比例',
    'moderate golden ratio': '中等黄金比例',
    'basic coordination': '基本协调',
    'needs improvement': '需要改善',
    'deviation': '偏差',
    'balanced': '平衡',
    'unbalanced': '不平衡',
    'symmetric': '对称',
    'asymmetric': '不对称',
    'golden ratio': '黄金比例',
    'ratio': '比例',
    'proportion': '比例',
    'proportions': '比例',
    
    // 脸型相关
    'oval': '椭圆形',
    'round': '圆形', 
    'square': '方形',
    'long': '长形',
    'heart': '心形',
    'diamond': '钻石形',
    'triangle': '三角形',
    'oblong': '长方形',
    'face shape': '脸型',
    'facial shape': '面部形状',
    
    // 面部特征相关
    'nose width': '鼻宽',
    'mouth width': '嘴宽',
    'eye distance': '眼距',
    'nose length': '鼻长',
    'jaw width': '下颌宽度',
    'cheekbone width': '颧骨宽度',
    'forehead width': '额头宽度',
    'facial width': '面部宽度',
    'facial height': '面部高度',
    'upper face': '上脸部',
    'middle face': '中脸部',
    'lower face': '下脸部',
    
    // 比例分析相关
    'ideal ratio': '理想比例',
    'actual ratio': '实际比例',
    'close to ideal': '接近理想',
    'far from ideal': '偏离理想',
    'perfect proportion': '完美比例',
    'good proportion': '良好比例',
    'poor proportion': '比例不佳',
    'three courts': '三庭',
    'three court analysis': '三庭分析',
    'five eyes': '五眼',
    'five eye analysis': '五眼分析',
    'upper court': '上庭',
    'middle court': '中庭',
    'lower court': '下庭',
    'eye gap': '眼间距',
    'left eye': '左眼',
    'right eye': '右眼',
    'left edge': '左侧边缘',
    'right edge': '右侧边缘',
    
    // 对称性相关
    'symmetry': '对称性',
    'symmetrical': '对称的',
    'asymmetrical': '不对称的',
    'left right balance': '左右平衡',
    'facial symmetry': '面部对称性',
    'bilateral symmetry': '双侧对称',
    
    // 特征描述相关
    'well coordinated': '协调良好',
    'poorly coordinated': '协调性差',
    'harmonious': '和谐',
    'inharmonious': '不和谐',
    'proportional': '比例协调',
    'disproportional': '比例失调',
    'coordinated': '协调',
    'uncoordinated': '不协调',
    'harmony': '和谐',
    'balance': '平衡',
    'imbalance': '不平衡',
    
    // 评分相关
    'excellent': '优秀',
    'very good': '很好',
    'good': '良好',
    'fair': '一般',
    'poor': '较差',
    'perfect': '完美',
    'outstanding': '出色',
    'superior': '卓越',
    'average': '平均',
    
    // 医美建议相关
    'slimmer': '更纤细',
    'slim': '纤细',
    'thinner': '更薄',
    'thicker': '更厚',
    'wider': '更宽',
    'narrower': '更窄',
    'longer': '更长',
    'shorter': '更短',
    'taller': '更高',
    'smaller': '更小',
    'larger': '更大',
    'bigger': '更大',
    'enhance': '增强',
    'reduce': '减少',
    'improve': '改善',
    'optimize': '优化',
    'adjust': '调整',
    'modify': '修改',
    'refine': '精细化',
    'contour': '轮廓',
    'highlight': '突出',
    'soften': '柔化',
    'define': '定义',
    'balance': '平衡',
    'proportion': '比例',
    'harmonize': '协调',
    'below average': '低于平均',
    'above average': '高于平均',
    'satisfactory': '满意',
    'unsatisfactory': '不满意',
    
    // 医美项目小标题翻译
    'face contouring': '面部轮廓塑形',
    'facial contouring': '面部轮廓塑形',
    'eye shape adjustment': '眼型调整',
    'nose and mouth optimization': '鼻唇优化',
    'nose optimization': '鼻部优化',
    'mouth optimization': '唇部优化',
    'lip enhancement': '唇部增强',
    'jawline enhancement': '下颌线增强',
    'cheek enhancement': '面颊增强',
    'forehead contouring': '额头塑形',
    
    // 非侵入性建议小标题
    'hairstyle suggestion': '发型建议',
    'hairstyle suggestions': '发型建议',
    'makeup suggestions': '化妆建议',
    'makeup advice': '化妆技巧',
    'skincare advice': '护肤建议',
    'skincare suggestions': '护肤建议',
    'styling tips': '造型技巧',
    'beauty tips': '美容技巧',
    
    // 个性化分析小标题
    'age-specific suggestions': '年龄定制建议',
    'gender-specific suggestions': '性别定制建议',
    'face shape specific': '脸型定制',
    'personalized tips': '个性化建议',
    
    // 数据分析小标题
    'key data analysis': '关键数据分析',
    'professional opinion': '专业意见',
    'measurement analysis': '测量分析',
    'proportion analysis': '比例分析',
    
    // 医美建议相关
    'recommend': '建议',
    'suggestion': '建议',
    'improvement': '改善',
    'enhancement': '提升',
    'optimization': '优化',
    'rhinoplasty': '鼻整形',
    'blepharoplasty': '眼部整形',
    'facelift': '面部提升',
    'jawline': '下颌线',
    'contouring': '轮廓塑形',
    'filler': '填充',
    'botox': '肉毒素',
    'cosmetic surgery': '整容手术',
    'aesthetic': '美学',
    'facial aesthetics': '面部美学',
    
    // 技术术语相关
    'algorithm': '算法',
    'confidence': '置信度',
    'detection': '检测',
    'analysis': '分析',
    'measurement': '测量',
    'calculation': '计算',
    'assessment': '评估',
    'evaluation': '评价',
    'score': '得分',
    'percentage': '百分比',
    'accuracy': '准确度',
    'precision': '精确度',
    
    // 方向位置相关
    'left': '左',
    'right': '右',
    'center': '中央',
    'upper': '上',
    'lower': '下',
    'middle': '中',
    'horizontal': '水平',
    'vertical': '垂直',
    'diagonal': '对角',
    
    // 数学统计相关
    'deviation': '偏差',
    'variance': '方差',
    'standard': '标准',
    'average': '平均',
    'median': '中位数',
    'maximum': '最大值',
    'minimum': '最小值',
    'range': '范围',
    'distribution': '分布',
    
    // 常见形容词
    'wide': '宽',
    'narrow': '窄',
    'broad': '宽阔',
    'thin': '薄',
    'thick': '厚',
    'small': '小',
    'large': '大',
    'medium': '中等',
    'sharp': '尖锐',
    'soft': '柔和',
    'strong': '强烈',
    'weak': '微弱',
    'prominent': '突出',
    'subtle': '细微',
    'defined': '清晰',
    'undefined': '模糊',
    'overall': '总体',
    'minimal': '最小',
    'multiple': '多个',
    'single': '单个',
    'few': '少数',
    'many': '许多',
    'several': '几个',
    'various': '各种',
    'different': '不同',
    'similar': '相似',
    'same': '相同',
    'other': '其他',
    'another': '另一个',
    'each': '每个',
    'every': '每个',
    'all': '所有',
    'both': '两个',
    'either': '任一',
    'neither': '都不',
    'some': '一些',
    'any': '任何',
    'none': '没有',
    'more': '更多',
    'less': '更少',
    'most': '最多',
    'least': '最少',
    'much': '很多',
    'little': '很少',
    'enough': '足够',
    'too': '太',
    'very': '非常',
    'quite': '相当',
    'rather': '相当',
    'fairly': '相当',
    'pretty': '相当',
    'really': '真的',
    'truly': '真正',
    'actually': '实际上',
    'certainly': '确实',
    'definitely': '绝对',
    'probably': '可能',
    'perhaps': '也许',
    'maybe': '也许',
    'possibly': '可能',
    'clearly': '明显地',
    'obviously': '显然',
    'apparently': '显然',
    'evidently': '明显地',
    'naturally': '自然地',
    'generally': '一般地',
    'usually': '通常',
    'normally': '正常地',
    'typically': '典型地',
    'commonly': '通常',
    'frequently': '经常',
    'often': '经常',
    'sometimes': '有时',
    'occasionally': '偶尔',
    'rarely': '很少',
    'seldom': '很少',
    'never': '从不',
    'always': '总是',
    'forever': '永远',
    'constantly': '持续地',
    'continuously': '连续地',
    'regularly': '定期地',
    'immediately': '立即',
    'instantly': '立即',
    'quickly': '快速地',
    'slowly': '缓慢地',
    'gradually': '逐渐地',
    'suddenly': '突然地',
    'finally': '最终',
    'eventually': '最终',
    'ultimately': '最终',
    'recently': '最近',
    'currently': '目前',
    'presently': '目前',
    'now': '现在',
    'today': '今天',
    'tomorrow': '明天',
    'yesterday': '昨天',
    'here': '这里',
    'there': '那里',
    'where': '哪里',
    'everywhere': '到处',
    'anywhere': '任何地方',
    'somewhere': '某处',
    'nowhere': '无处',
    'inside': '内部',
    'outside': '外部',
    'above': '上面',
    'below': '下面',
    'around': '周围',
    'between': '之间',
    'among': '在...中',
    'through': '通过',
    'across': '穿过',
    'along': '沿着',
    'towards': '朝向',
    'away': '远离',
    'near': '附近',
    'far': '远',
    'close': '近',
    'together': '一起',
    'apart': '分开',
    'alone': '单独',
    'only': '只有',
    'just': '只是',
    'still': '仍然',
    'yet': '还',
    'already': '已经',
    'soon': '很快',
    'later': '稍后',
    'before': '之前',
    'after': '之后',
    'during': '期间',
    'while': '当...时',
    'until': '直到',
    'since': '自从',
    'ago': '之前',
    'next': '下一个',
    'last': '最后',
    'first': '第一',
    'second': '第二',
    'third': '第三',
    'fourth': '第四',
    'fifth': '第五',
    
    // 年龄性别相关
    'male': '男性',
    'female': '女性',
    'young': '年轻',
    'mature': '成熟',
    'elderly': '年长',
    'adult': '成年',
    'teenager': '青少年',
    'middle aged': '中年',
    
    // 表情相关
    'neutral': '平静',
    'happy': '开心',
    'sad': '悲伤',
    'angry': '愤怒',
    'surprised': '惊讶',
    'fearful': '恐惧',
    'disgusted': '厌恶',
    'expression': '表情',
    'emotion': '情绪',
    'facial expression': '面部表情',
    
    // 基础英文词汇
    'the': '',
    'a': '',
    'an': '',
    'and': '和',
    'or': '或',
    'with': '具有',
    'without': '没有',
    'from': '从',
    'to': '到',
    'for': '为了',
    'in': '在',
    'on': '在',
    'at': '在',
    'by': '通过',
    'of': '的',
    'is': '是',
    'are': '是',
    'was': '是',
    'were': '是',
    'be': '是',
    'been': '是',
    'being': '是',
    'have': '有',
    'has': '有',
    'had': '有',
    'will': '将',
    'would': '将',
    'can': '能',
    'could': '能',
    'should': '应该',
    'may': '可能',
    'might': '可能',
    'must': '必须',
    'shall': '应该',
    'that': '那个',
    'this': '这个',
    'these': '这些',
    'those': '那些',
    'show': '显示',
    'shows': '显示',
    'showing': '显示',
    'shown': '显示',
    'reveal': '显示',
    'reveals': '显示',
    'revealing': '显示',
    'revealed': '显示',
    'indicate': '表明',
    'indicates': '表明',
    'indicating': '表明',
    'indicated': '表明',
    'suggest': '建议',
    'suggests': '建议',
    'suggesting': '建议',
    'suggested': '建议',
    'display': '展现',
    'displays': '展现',
    'displaying': '展现',
    'displayed': '展现',
    'demonstrate': '证明',
    'demonstrates': '证明',
    'demonstrating': '证明',
    'demonstrated': '证明',
    'present': '呈现',
    'presents': '呈现',
    'presenting': '呈现',
    'presented': '呈现',
    'appear': '显现',
    'appears': '显现',
    'appearing': '显现',
    'appeared': '显现',
    'seem': '似乎',
    'seems': '似乎',
    'seeming': '似乎',
    'seemed': '似乎',
    'look': '看起来',
    'looks': '看起来',
    'looking': '看起来',
    'looked': '看起来',
    'feature': '特征',
    'features': '特征',
    'facial': '面部',
    'face': '面部',
    'result': '结果',
    'results': '结果',
    'resulting': '结果',
    'resulted': '结果',
    'finding': '发现',
    'findings': '发现',
    'observation': '观察',
    'observations': '观察',
    'conclusion': '结论',
    'conclusions': '结论',
    'assessment': '评估',
    'assessments': '评估',
    'evaluation': '评价',
    'evaluations': '评价',
    'recommendation': '建议',
    'recommendations': '建议',
    'suggestion': '建议',
    'suggestions': '建议',
    'advice': '建议',
    'guidance': '指导',
    'tip': '提示',
    'tips': '提示',
    'note': '注意',
    'notes': '注意',
    'comment': '评论',
    'comments': '评论',
    'remark': '备注',
    'remarks': '备注',
    'overall': '总体',
    'general': '总体',
    'specific': '具体',
    'particular': '特定',
    'individual': '个别',
    'personal': '个人',
    'unique': '独特',
    'special': '特殊',
    'normal': '正常',
    'typical': '典型',
    'common': '常见',
    'unusual': '不寻常',
    'rare': '罕见',
    'frequent': '频繁',
    'occasional': '偶尔',
    'regular': '规律',
    'irregular': '不规律',
    'consistent': '一致',
    'inconsistent': '不一致',
    'stable': '稳定',
    'unstable': '不稳定',
    'steady': '稳定',
    'variable': '变化',
    'constant': '恒定',
    'changing': '变化',
    'improving': '改善',
    'worsening': '恶化',
    'maintaining': '保持',
    'increasing': '增加',
    'decreasing': '减少',
    'rising': '上升',
    'falling': '下降',
    'growing': '增长',
    'shrinking': '缩小',
    'expanding': '扩大',
    'contracting': '收缩',
    'developing': '发展',
    'progressing': '进步',
    'advancing': '进步',
    'declining': '衰退',
    'deteriorating': '恶化',
    'enhancing': '增强',
    'strengthening': '加强',
    'weakening': '减弱',
    'optimizing': '优化',
    'maximizing': '最大化',
    'minimizing': '最小化',
    'achieving': '达到',
    'reaching': '达到',
    'attaining': '获得',
    'obtaining': '获得',
    'gaining': '获得',
    'losing': '失去',
    'missing': '缺少',
    'lacking': '缺乏',
    'needing': '需要',
    'requiring': '需要',
    'demanding': '要求',
    'expecting': '期望',
    'hoping': '希望',
    'wishing': '希望',
    'wanting': '想要',
    'desiring': '渴望',
    'seeking': '寻求',
    'searching': '寻找',
    'finding': '发现',
    'discovering': '发现',
    'uncovering': '发现',
    'detecting': '检测',
    'identifying': '识别',
    'recognizing': '识别',
    'distinguishing': '区分',
    'differentiating': '区分',
    'comparing': '比较',
    'contrasting': '对比',
    'matching': '匹配',
    'corresponding': '对应',
    'relating': '相关',
    'connecting': '连接',
    'linking': '连接',
    'associating': '关联',
    'combining': '结合',
    'merging': '合并',
    'integrating': '整合',
    'unifying': '统一',
    'separating': '分离',
    'dividing': '分割',
    'splitting': '分裂',
    'breaking': '打破',
    'fracturing': '断裂',
    'damaging': '损坏',
    'harming': '伤害',
    'injuring': '受伤',
    'healing': '愈合',
    'recovering': '恢复',
    'restoring': '恢复',
    'repairing': '修复',
    'fixing': '修复',
    'correcting': '纠正',
    'adjusting': '调整',
    'modifying': '修改',
    'changing': '改变',
    'altering': '改变',
    'transforming': '转换',
    'converting': '转换',
    'adapting': '适应',
    'accommodating': '适应',
    'fitting': '合适',
    'suiting': '适合',
    'matching': '匹配',
    'coordinating': '协调',
    'balancing': '平衡',
    'stabilizing': '稳定',
    'securing': '确保',
    'protecting': '保护',
    'defending': '防护',
    'supporting': '支持',
    'maintaining': '维持',
    'preserving': '保持',
    'conserving': '保存',
    'saving': '拯救',
    'rescuing': '拯救',
    'helping': '帮助',
    'assisting': '协助',
    'aiding': '援助',
    'serving': '服务',
    'providing': '提供',
    'offering': '提供',
    'giving': '给予',
    'delivering': '交付',
    'supplying': '供应',
    'furnishing': '提供',
    'equipping': '装备',
    'preparing': '准备',
    'arranging': '安排',
    'organizing': '组织',
    'planning': '计划',
    'designing': '设计',
    'creating': '创造',
    'building': '建造',
    'constructing': '构建',
    'developing': '开发',
    'producing': '产生',
    'generating': '生成',
    'forming': '形成',
    'shaping': '塑造',
    'molding': '塑造',
    'sculpting': '雕刻',
    'carving': '雕刻',
    'cutting': '切割',
    'trimming': '修剪',
    'polishing': '抛光',
    'refining': '精炼',
    'perfecting': '完善',
    'finishing': '完成',
    'completing': '完成',
    'concluding': '结束',
    'ending': '结束',
    'terminating': '终止',
    'stopping': '停止',
    'ceasing': '停止',
    'pausing': '暂停',
    'halting': '停止',
    'continuing': '继续',
    'proceeding': '进行',
    'advancing': '前进',
    'moving': '移动',
    'shifting': '转移',
    'transferring': '转移',
    'transporting': '运输',
    'carrying': '携带',
    'bearing': '承受',
    'holding': '持有',
    'grasping': '抓住',
    'gripping': '抓紧',
    'clutching': '紧握',
    'embracing': '拥抱',
    'hugging': '拥抱',
    'surrounding': '围绕',
    'enclosing': '包围',
    'containing': '包含',
    'including': '包括',
    'comprising': '包含',
    'consisting': '组成',
    'constituting': '构成',
    'representing': '代表',
    'symbolizing': '象征',
    'signifying': '意味',
    'meaning': '意思',
    'implying': '暗示',
    'suggesting': '建议',
    'hinting': '暗示',
    'indicating': '表明',
    'pointing': '指向',
    'directing': '指导',
    'guiding': '引导',
    'leading': '引导',
    'following': '跟随',
    'tracking': '跟踪',
    'monitoring': '监控',
    'watching': '观察',
    'observing': '观察',
    'viewing': '查看',
    'seeing': '看到',
    'noticing': '注意到',
    'perceiving': '感知',
    'sensing': '感觉',
    'feeling': '感觉',
    'experiencing': '体验',
    'undergoing': '经历',
    'suffering': '遭受',
    'enduring': '忍受',
    'tolerating': '容忍',
    'accepting': '接受',
    'approving': '批准',
    'agreeing': '同意',
    'consenting': '同意',
    'permitting': '允许',
    'allowing': '允许',
    'enabling': '使能够',
    'facilitating': '促进',
    'encouraging': '鼓励',
    'motivating': '激励',
    'inspiring': '启发',
    'stimulating': '刺激',
    'exciting': '兴奋',
    'thrilling': '激动',
    'amazing': '令人惊奇',
    'surprising': '令人惊讶',
    'shocking': '令人震惊',
    'stunning': '令人震惊',
    'astonishing': '令人惊讶',
    'remarkable': '显著',
    'notable': '值得注意',
    'significant': '重要',
    'important': '重要',
    'crucial': '关键',
    'critical': '关键',
    'essential': '基本',
    'fundamental': '基本',
    'basic': '基本',
    'primary': '主要',
    'main': '主要',
    'major': '主要',
    'minor': '次要',
    'secondary': '次要',
    'additional': '额外',
    'extra': '额外',
    'supplementary': '补充',
    'complementary': '互补',
    'alternative': '替代',
    'optional': '可选',
    'possible': '可能',
    'probable': '可能',
    'likely': '可能',
    'unlikely': '不太可能',
    'impossible': '不可能',
    'certain': '确定',
    'sure': '确定',
    'definite': '明确',
    'clear': '清楚',
    'obvious': '明显',
    'evident': '明显',
    'apparent': '显然',
    'visible': '可见',
    'invisible': '不可见',
    'hidden': '隐藏',
    'secret': '秘密',
    'private': '私人',
    'public': '公开',
    'open': '开放',
    'closed': '关闭',
    'available': '可用',
    'unavailable': '不可用',
    'accessible': '可访问',
    'inaccessible': '不可访问',
    'reachable': '可达到',
    'unreachable': '不可达到',
    'achievable': '可实现',
    'unachievable': '不可实现',
    'realistic': '现实',
    'unrealistic': '不现实',
    'practical': '实用',
    'impractical': '不实用',
    'useful': '有用',
    'useless': '无用',
    'helpful': '有帮助',
    'unhelpful': '无帮助',
    'beneficial': '有益',
    'harmful': '有害',
    'positive': '积极',
    'negative': '消极',
    'favorable': '有利',
    'unfavorable': '不利',
    'advantageous': '有利',
    'disadvantageous': '不利',
    'profitable': '有利可图',
    'unprofitable': '无利可图',
    'successful': '成功',
    'unsuccessful': '不成功',
    'effective': '有效',
    'ineffective': '无效',
    'efficient': '高效',
    'inefficient': '低效',
    'productive': '高效',
    'unproductive': '低效',
    'valuable': '有价值',
    'invaluable': '无价',
    'worthless': '无价值',
    'precious': '珍贵',
    'cheap': '便宜',
    'expensive': '昂贵',
    'costly': '昂贵',
    'affordable': '负担得起',
    'unaffordable': '负担不起'
  };
  
  let translatedText = text;
  
  // 执行翻译替换
  for (const [english, chinese] of Object.entries(analysisTranslations)) {
    const regex = new RegExp(english, 'gi');
    translatedText = translatedText.replace(regex, chinese);
  }
  
  // 执行多轮翻译，确保彻底转换
  for (let round = 0; round < 3 && /[a-zA-Z]/.test(translatedText); round++) {
    const beforeRound = translatedText;
    
    // 第二轮翻译：处理数字和单位
    if (round === 1) {
      translatedText = translatedText
        .replace(/\bpixels?\b/gi, '像素')
        .replace(/\bpx\b/gi, '像素')
        .replace(/\bpercent\b/gi, '百分比')
        .replace(/\bpercentage\b/gi, '百分比')
        .replace(/\bdegrees?\b/gi, '度')
        .replace(/\bmillimeters?\b/gi, '毫米')
        .replace(/\bmm\b/gi, '毫米')
        .replace(/\bcentimeters?\b/gi, '厘米')
        .replace(/\bcm\b/gi, '厘米')
        .replace(/\bratio\s*[:=]\s*/gi, '比例：')
        .replace(/\bscore\s*[:=]\s*/gi, '得分：')
        .replace(/\bwidth\s*[:=]\s*/gi, '宽度：')
        .replace(/\bheight\s*[:=]\s*/gi, '高度：')
        .replace(/\blength\s*[:=]\s*/gi, '长度：');
    }
    
    // 第三轮翻译：处理常见短语和组合词
    if (round === 2) {
      translatedText = translatedText
        .replace(/\bface\s*shape\b/gi, '脸型')
        .replace(/\bgolden\s*ratio\b/gi, '黄金比例')
        .replace(/\bfacial\s*features?\b/gi, '面部特征')
        .replace(/\bbeauty\s*score\b/gi, '美丽评分')
        .replace(/\bconfidence\s*level\b/gi, '置信水平')
        .replace(/\banalysis\s*result\b/gi, '分析结果')
        .replace(/\boverall\s*assessment\b/gi, '综合评估')
        .replace(/\brecommendation\b/gi, '建议')
        .replace(/\bsuggestion\b/gi, '建议')
        .replace(/\bimprovement\b/gi, '改善')
        .replace(/\benhancement\b/gi, '提升');
    }
    
    if (beforeRound === translatedText) break; // 没有变化就停止
  }
  
  // 最终检查并记录
  const hasEnglish = /[a-zA-Z]/.test(translatedText);
  if (hasEnglish && translatedText !== text) {
    console.log(`🔄 分析文本翻译: "${text}" → "${translatedText}"`);
    console.log(`⚠️ 仍有英文残留: "${translatedText.match(/[a-zA-Z]+/g)?.join(', ')}"`);
  } else if (hasEnglish) {
    console.log(`⚠️ 检测到未翻译的英文内容: "${text}"`);
    console.log(`📝 英文词汇: "${translatedText.match(/[a-zA-Z]+/g)?.join(', ')}"`);
  } else if (translatedText !== text) {
    console.log(`✅ 翻译成功: "${text}" → "${translatedText}"`);
  }
  
  return translatedText;
}

// 键名翻译映射表
const keyTranslations = {
  // 黄金比例相关键名
  'threeCourts': '三庭',
  'noseMouthWidth': '鼻嘴宽度',
  'threeEyes': '三眼',
  'faceRatio': '面部比例',
  'noseMouthRelation': '鼻嘴关系',
  'eyebrowEyeRatio': '眉眼比例',
  
  // 具体数值键名
  'upperRatio': '上庭比例',
  'middleRatio': '中庭比例', 
  'lowerRatio': '下庭比例',
  'leftEyeRatio': '左眼比例',
  'eyeGapRatio': '眼间距比例',
  'rightEyeRatio': '右眼比例',
  'actualRatio': '实际比例',
  'idealRatio': '理想比例',
  'noseWidth': '鼻宽',
  'mouthWidth': '嘴宽',
  'leftRightBalance': '左右平衡',
  'isSymmetric': '是否对称',
  'isBalanced': '是否平衡',
  'isGoldenRatio': '是否黄金比例',
  
  // 分析相关键名  
  'goldenRatio': '黄金比例',
  'analysis': '分析',
  'score': '得分',
  'deviation': '偏差',
  'confidence': '置信度',
  'algorithm': '算法',
  'reason': '原因',
  
  // 面部特征键名
  'faceShape': '脸型',
  'eyeDistance': '眼距',
  'noseLength': '鼻长',
  'jawWidth': '下颌宽度',
  'cheekboneWidth': '颧骨宽度', 
  'foreheadWidth': '额头宽度',
  'eyeDistanceRatio': '眼距比例',
  'noseWidthRatio': '鼻宽比例',
  'mouthWidthRatio': '嘴宽比例',
  'jawToFaceRatio': '下颌脸部比例',
  'cheekToFaceRatio': '颧骨脸部比例',
  'foreheadToFaceRatio': '额头脸部比例',
  'faceDimensions': '面部尺寸',
  'measurements': '测量数据',
  
  // 比例分析键名
  'threeCourtAnalysis': '三庭分析',
  'fiveEyeAnalysis': '五眼分析',
  'leftEdge': '左侧边缘',
  'leftEye': '左眼',
  'eyeGap': '眼间距',
  'rightEye': '右眼', 
  'rightEdge': '右侧边缘',
  'upper': '上庭',
  'middle': '中庭',
  'lower': '下庭',
  'symmetry': '对称性',
  
  // 表情和情绪键名
  'expressions': '表情',
  'dominant': '主要',
  'dominantOriginal': '原始主要',
  'scores': '分数',
  'scoresOriginal': '原始分数',
  
  // 其他通用键名
  'width': '宽度',
  'height': '高度',
  'ratio': '比例',
  'proportions': '比例',
  'features': '特征',
  'boundingBox': '边界框',
  'landmarks': '关键点',
  'gender': '性别',
  'age': '年龄',
  'ageRange': '年龄段',
  'probability': '概率',
  'imageInfo': '图片信息',
  'faceCount': '人脸数量',
  'success': '成功',
  'timestamp': '时间戳',
  'details': '详情',
  
  // 补充遗漏的键名
  'faceShapeEn': '英文脸型',
  'beautifyRecommendations': '美化建议',
  'type': '类型',
  'suggestion': '建议',
  'recommendations': '建议',
  'x': 'x坐标',
  'y': 'y坐标',
  'path': '路径',
  'url': '链接',
  'name': '名称',
  'uploadTime': '上传时间',
  'id': '标识',
  '_id': '标识',
  'data': '数据',
  'code': '代码',
  'message': '消息',
  'faceIndex': '人脸索引',
  'jaw': '下颌',
  'leftEyebrow': '左眉毛',
  'rightEyebrow': '右眉毛',
  'nose': '鼻子',
  'mouth': '嘴巴',
  
  // Summary相关键名
  'summary': '总结',
  'strengths': '优势特征',
  'improvements': '可优化方面',
  'grade': '评级',
  'totalScore': '总分'
};

// 递归翻译对象中的所有文本内容，同时保留原键名并添加中文键名（双键方案）
// 注意：为了不影响前端基于英文枚举判断性别，显式跳过对 gender.gender 字段值的翻译
function translateObjectTexts(obj, currentKey) {
  if (typeof obj === 'string') {
    // 对于性别英文枚举，保持原样，避免把 'male'/'female' 翻译成中文
    if ((currentKey === 'gender' || currentKey === 'genderEn') && (obj === 'male' || obj === 'female')) {
      return obj;
    }
    return translateAnalysisText(obj);
  } else if (Array.isArray(obj)) {
    return obj.map(item => translateObjectTexts(item));
  } else if (obj && typeof obj === 'object') {
    const translatedObj = {};
    for (const [key, value] of Object.entries(obj)) {
      // 递归翻译值，并把当前 key 传递下去，便于有选择地跳过翻译
      const translatedValue = translateObjectTexts(value, key);
      
      // 保留原键名
      translatedObj[key] = translatedValue;
      
      // 如果有中文翻译键名，则添加中文键名版本
      const chineseKey = keyTranslations[key];
      if (chineseKey && chineseKey !== key) {
        translatedObj[chineseKey] = translatedValue;
      }
    }
    return translatedObj;
  }
  return obj;
}

// 获取年龄范围的辅助函数
function getAgeRange(age) {
  if (age < 18) return '未成年 (0-17岁)'
  else if (age < 25) return '青年 (18-24岁)'
  else if (age < 35) return '成年早期 (25-34岁)'
  else if (age < 45) return '成年中期 (35-44岁)'
  else if (age < 55) return '成年后期 (45-54岁)'
  else if (age < 65) return '中老年 (55-64岁)'
  else if (age < 75) return '老年 (65-74岁)'
  else return '高龄 (75岁以上)'
}

// 获取面部长宽比评级（不是黄金比例）
function getFaceRatioGrade(ratio) {
  if (ratio >= 1.3 && ratio <= 1.5) {
    return '理想长宽比'
  } else if (ratio >= 1.2 && ratio <= 1.6) {
    return '协调长宽比'
  } else if (ratio >= 1.1 && ratio <= 1.7) {
    return '良好长宽比'
  } else if (ratio < 1.0) {
    return '偏宽脸型'
  } else if (ratio > 1.8) {
    return '偏长脸型'
  } else {
    return '一般长宽比'
  }
}

// 计算两点间距离
function calculateDistance(point1, point2) {
  const dx = point1.x - point2.x
  const dy = point1.y - point2.y
  return Math.sqrt(dx * dx + dy * dy)
}

// 计算面部特征
function calculateFaceFeatures(landmarks, box) {
  try {
    const jaw = landmarks.getJawOutline()
    const leftEye = landmarks.getLeftEye()
    const rightEye = landmarks.getRightEye()
    const nose = landmarks.getNose()
    const mouth = landmarks.getMouth()
    
    // 计算眼距
    const leftEyeCenter = {
      x: leftEye.reduce((sum, p) => sum + p.x, 0) / leftEye.length,
      y: leftEye.reduce((sum, p) => sum + p.y, 0) / leftEye.length
    }
    const rightEyeCenter = {
      x: rightEye.reduce((sum, p) => sum + p.x, 0) / rightEye.length,
      y: rightEye.reduce((sum, p) => sum + p.y, 0) / rightEye.length
    }
    const eyeDistance = calculateDistance(leftEyeCenter, rightEyeCenter)
    
    // 计算鼻子长度 (鼻尖到鼻根)
    const noseLength = calculateDistance(nose[0], nose[3])
    
    // 计算嘴巴宽度
    const mouthWidth = calculateDistance(mouth[0], mouth[8])
    
    // 分析脸型 - 改进算法
    const faceWidth = Math.abs(jaw[16].x - jaw[0].x)
    const faceHeight = Math.abs(jaw[8].y - jaw[0].y)
    const faceRatio = faceHeight / faceWidth
    
    // 计算下颌宽度（颧骨位置）
    const cheekboneWidth = Math.abs(jaw[4].x - jaw[12].x)
    const jawWidth = Math.abs(jaw[6].x - jaw[10].x) // 下颌最宽处
    
    // 计算额头宽度（通过眉毛位置估算）
    const foreheadWidth = Math.abs(landmarks.getLeftEyeBrow()[0].x - landmarks.getRightEyeBrow()[4].x)
    
    // 详细调试信息
    console.log('🔍 脸型分析原始数据:')
    console.log(`   - 脸宽: ${faceWidth.toFixed(1)} px`)
    console.log(`   - 脸高: ${faceHeight.toFixed(1)} px`)
    console.log(`   - 长宽比: ${faceRatio.toFixed(3)}`)
    console.log(`   - 颧骨宽: ${cheekboneWidth.toFixed(1)} px`)
    console.log(`   - 下颌宽: ${jawWidth.toFixed(1)} px`)
    console.log(`   - 额头宽: ${foreheadWidth.toFixed(1)} px`)
    
    // 计算各种比例
    const cheekToFaceRatio = cheekboneWidth / faceWidth
    const jawToFaceRatio = jawWidth / faceWidth
    const foreheadToFaceRatio = foreheadWidth / faceWidth
    
    console.log('📊 脸型关键比例:')
    console.log(`   - 颧骨/脸宽比: ${cheekToFaceRatio.toFixed(3)}`)
    console.log(`   - 下颌/脸宽比: ${jawToFaceRatio.toFixed(3)}`)
    console.log(`   - 额头/脸宽比: ${foreheadToFaceRatio.toFixed(3)}`)
    
    console.log('🎯 当前阈值对比检查:')
    console.log(`   圆脸检查:`)
    console.log(`     ✓ 长宽比 ${faceRatio.toFixed(3)} < 0.98? ${faceRatio < 0.98 ? '是' : '否'}`)
    console.log(`     ✓ 下颌比 ${jawToFaceRatio.toFixed(3)} > 0.80? ${jawToFaceRatio > 0.80 ? '是' : '否'}`)
    console.log(`     ✓ 颧骨比 ${cheekToFaceRatio.toFixed(3)} > 0.78? ${cheekToFaceRatio > 0.78 ? '是' : '否'}`)
    console.log(`   方脸检查:`)
    console.log(`     ✓ 下颌比 ${jawToFaceRatio.toFixed(3)} > 0.88? ${jawToFaceRatio > 0.88 ? '是' : '否'}`)
    console.log(`     ✓ 颧骨比 ${cheekToFaceRatio.toFixed(3)} > 0.85? ${cheekToFaceRatio > 0.85 ? '是' : '否'}`)
    console.log(`     ✓ 长宽比 ${faceRatio.toFixed(3)} 在0.95-1.15? ${faceRatio >= 0.95 && faceRatio <= 1.15 ? '是' : '否'}`)
    console.log(`   长脸检查:`)
    console.log(`     ✓ 长宽比 ${faceRatio.toFixed(3)} > 1.45? ${faceRatio > 1.45 ? '是' : '否'}`)
    console.log(`   心形脸检查:`)
    console.log(`     ✓ 额头比 ${foreheadToFaceRatio.toFixed(3)} > 0.90? ${foreheadToFaceRatio > 0.90 ? '是' : '否'}`)
    console.log(`     ✓ 下颌比 ${jawToFaceRatio.toFixed(3)} < 0.72? ${jawToFaceRatio < 0.72 ? '是' : '否'}`)
    console.log(`   椭圆脸检查:`)
    console.log(`     ✓ 长宽比 ${faceRatio.toFixed(3)} 在1.20-1.38? ${faceRatio >= 1.20 && faceRatio <= 1.38 ? '是' : '否'}`)
    console.log(`     ✓ 下颌比 ${jawToFaceRatio.toFixed(3)} 在0.72-0.85? ${jawToFaceRatio >= 0.72 && jawToFaceRatio <= 0.85 ? '是' : '否'}`)
    console.log(`     ✓ 颧骨比 ${cheekToFaceRatio.toFixed(3)} 在0.75-0.85? ${cheekToFaceRatio >= 0.75 && cheekToFaceRatio <= 0.85 ? '是' : '否'}`)
    
    // 基于实际数据重新设计的脸型判断逻辑
    let faceShape = 'oval' // 默认
    let confidence = 0
    let reason = ''
    
    console.log('🔍 应用新的脸型判断算法 (基于实际数据优化):')
    
    // 基于实际数据的优化判断逻辑
    if (faceRatio > 1.30) {
      // 长脸：根据数据，长宽比应该更接近实际
      faceShape = 'long'
      confidence = Math.min(90, 60 + (faceRatio - 1.30) * 150)
      reason = `长宽比${faceRatio.toFixed(3)} > 1.30，判断为长脸`
    } else if (faceRatio < 0.75 && jawToFaceRatio > 0.60 && cheekToFaceRatio > 0.85) {
      // 圆脸：超严格条件，只有真正很圆的才算
      faceShape = 'round'
      confidence = Math.min(90, 70 + (0.75 - faceRatio) * 200)
      reason = `长宽比${faceRatio.toFixed(3)} < 0.75且下颌比${jawToFaceRatio.toFixed(3)} > 0.60且颧骨比${cheekToFaceRatio.toFixed(3)} > 0.85，判断为圆脸`
    } else if (jawToFaceRatio > 0.65 && cheekToFaceRatio > 0.85 && faceRatio >= 0.85 && faceRatio <= 1.10) {
      // 方脸：下颌和颧骨都宽，长宽比适中
      faceShape = 'square'
      confidence = Math.min(90, 60 + (jawToFaceRatio - 0.65) * 200)
      reason = `下颌比${jawToFaceRatio.toFixed(3)} > 0.65且颧骨比${cheekToFaceRatio.toFixed(3)} > 0.85，长宽比${faceRatio.toFixed(3)}适中，判断为方脸`
    } else if (foreheadToFaceRatio > 0.85 && jawToFaceRatio < 0.55) {
      // 心形脸：额头宽下颌窄
      faceShape = 'heart'
      confidence = Math.min(90, 60 + (foreheadToFaceRatio - 0.85) * 300)
      reason = `额头比${foreheadToFaceRatio.toFixed(3)} > 0.85且下颌比${jawToFaceRatio.toFixed(3)} < 0.55，判断为心形脸`
    } else if (faceRatio >= 1.05 && faceRatio <= 1.25 && jawToFaceRatio >= 0.45 && jawToFaceRatio <= 0.65 && cheekToFaceRatio >= 0.75 && cheekToFaceRatio <= 0.85) {
      // 椭圆脸：基于实际数据的理想范围
      faceShape = 'oval'
      confidence = 85
      reason = `长宽比${faceRatio.toFixed(3)}在优化范围(1.05-1.25)，下颌比${jawToFaceRatio.toFixed(3)}合理，颧骨比${cheekToFaceRatio.toFixed(3)}协调，判断为椭圆脸`
    } else {
      // 基于主要特征的倾向性判断
      if (faceRatio > 1.25) {
        faceShape = 'long'
        confidence = 70
        reason = `长宽比${faceRatio.toFixed(3)} > 1.25，倾向于长脸`
      } else if (faceRatio < 0.78) {
        faceShape = 'round'
        confidence = 65
        reason = `长宽比${faceRatio.toFixed(3)} < 0.78，倾向于圆脸`
      } else if (jawToFaceRatio > 0.58 && faceRatio >= 0.80 && faceRatio <= 1.15) {
        faceShape = 'square'
        confidence = 70
        reason = `下颌比${jawToFaceRatio.toFixed(3)} > 0.58且长宽比${faceRatio.toFixed(3)}适中，倾向于方脸`
      } else if (foreheadToFaceRatio > 0.82 && jawToFaceRatio < 0.52) {
        faceShape = 'heart'
        confidence = 70
        reason = `额头比${foreheadToFaceRatio.toFixed(3)} > 0.82且下颌比${jawToFaceRatio.toFixed(3)} < 0.52，倾向于心形脸`
      } else {
        // 基于长宽比的最终判断
        if (faceRatio >= 0.78 && faceRatio <= 1.25) {
          faceShape = 'oval'
          confidence = 75
          reason = `长宽比${faceRatio.toFixed(3)}在正常范围内，下颌比${jawToFaceRatio.toFixed(3)}，判断为椭圆脸`
        } else if (faceRatio > 1.25) {
          faceShape = 'long'
          confidence = 60
          reason = `长宽比${faceRatio.toFixed(3)}偏高，默认为长脸`
        } else {
          faceShape = 'round'
          confidence = 60
          reason = `长宽比${faceRatio.toFixed(3)}偏低，默认为圆脸`
        }
      }
    }
    
    console.log(`🎯 脸型判断结果: ${faceShape} (置信度: ${confidence.toFixed(1)}%)`)
    console.log(`📝 判断理由: ${reason}`)
    
    // 收集样本数据用于统计分析
    addFaceShapeSample({
      faceRatio: faceRatio,
      jawRatio: jawToFaceRatio,
      cheekRatio: cheekToFaceRatio,
      foreheadRatio: foreheadToFaceRatio,
      result: faceShape,
      confidence: confidence,
      timestamp: new Date().toISOString()
    })
    
    // 输出新的脸型判断参考表
    console.log('📋 新的脸型判断标准 (基于实际数据优化):')
    console.log('   圆脸: 长宽比 < 0.75 且 下颌比 > 0.60 且 颧骨比 > 0.85')
    console.log('   方脸: 下颌比 > 0.65 且 颧骨比 > 0.85 且 长宽比 0.85-1.10')
    console.log('   长脸: 长宽比 > 1.30')
    console.log('   心形脸: 额头比 > 0.85 且 下颌比 < 0.55')
    console.log('   椭圆脸: 长宽比 1.05-1.25 且 下颌比 0.45-0.65 且 颧骨比 0.75-0.85')
    console.log('   倾向判断: 长宽比 0.78-1.25 默认椭圆脸')
    console.log('─'.repeat(50))
    
    const faceShapeMap = {
      'oval': '椭圆形',
      'round': '圆形',
      'square': '方形', 
      'long': '长形',
      'heart': '心形'
    }
    
    return {
      faceShape: faceShapeMap[faceShape] || '椭圆形',
      faceShapeEn: faceShape,
      eyeDistance: Math.round(eyeDistance * 10) / 10,
      noseLength: Math.round(noseLength * 10) / 10,
      mouthWidth: Math.round(mouthWidth * 10) / 10,
      faceDimensions: {
        width: Math.round(faceWidth),
        height: Math.round(faceHeight),
        ratio: Math.round(faceRatio * 100) / 100
      },
      measurements: {
        jawWidth: Math.round(jawWidth),
        cheekboneWidth: Math.round(cheekboneWidth),
        foreheadWidth: Math.round(foreheadWidth),
        eyeDistanceRatio: Math.round((eyeDistance / faceWidth) * 100) / 100,
        noseWidthRatio: Math.round((Math.abs(nose[4].x - nose[0].x) / faceWidth) * 100) / 100,
        mouthWidthRatio: Math.round((mouthWidth / faceWidth) * 100) / 100,
        jawToFaceRatio: Math.round(jawToFaceRatio * 100) / 100,
        cheekToFaceRatio: Math.round(cheekToFaceRatio * 100) / 100,
        foreheadToFaceRatio: Math.round(foreheadToFaceRatio * 100) / 100
      },
      analysis: {
        confidence: Math.round(confidence),
        reason: reason,
        algorithm: 'improved_multi_factor'
      }
    }
  } catch (error) {
    console.error('计算面部特征失败:', error)
    return {
      faceShape: '无法分析',
      eyeDistance: 0,
      noseLength: 0,
      mouthWidth: 0,
      faceDimensions: { width: 0, height: 0, ratio: 0 },
      error: error.message
    }
  }
}

// 从黄金比例结果转换为基础比例分析格式
function convertGoldenRatioToProportions(goldenRatioResult) {
  try {
    
    if (!goldenRatioResult || !goldenRatioResult.details) {
      throw new Error('黄金比例数据不可用')
    }
    
    const details = goldenRatioResult.details
    
    // 面部长宽比数据
    const faceRatioData = details.faceRatio || {}
    const faceRatio = faceRatioData.actualRatio || 0
    
    // 三庭分析数据
    const threeCourtData = details.threeCourts || {}
    const threeCourtAnalysis = {
      upper: Math.round(threeCourtData.upperRatio || 0),
      middle: Math.round(threeCourtData.middleRatio || 0),
      lower: Math.round(threeCourtData.lowerRatio || 0),
      isBalanced: threeCourtData.score >= 80
    }
    
    // 三眼分析数据
    const threeEyeData = details.threeEyes || {}
    const threeEyeAnalysis = {
      leftEye: Math.round((threeEyeData.leftEyeRatio || 0.33) * 100) / 100,
      eyeGap: Math.round((threeEyeData.eyeGapRatio || 0.33) * 100) / 100,
      rightEye: Math.round((threeEyeData.rightEyeRatio || 0.33) * 100) / 100,
      isBalanced: threeEyeData.score >= 75  // 降低阈值从80到75
    }
    
    
    return {
      // 面部长宽比
      faceRatio: Math.round(faceRatio * 100) / 100,
      faceRatioGrade: getFaceRatioGrade(faceRatio),
      
      // 三庭分析 
      threeCourtAnalysis: threeCourtAnalysis,
      
      // 三眼分析
      threeEyeAnalysis: threeEyeAnalysis,
      
      // 基础对称性分析（从眉眼比例计算）
      symmetry: {
        leftRightBalance: Math.round((details.eyebrowEyeRatio?.deviation || 0) * 100) / 100,
        isSymmetric: (details.eyebrowEyeRatio?.score || 0) >= 70
      }
    }
  } catch (error) {
    console.error('转换黄金比例数据失败:', error)
    return {
      faceRatio: 0,
      faceRatioGrade: '数据转换失败',
      threeCourtAnalysis: { isBalanced: false },
      threeEyeAnalysis: { isBalanced: false },
      symmetry: { leftRightBalance: 0, isSymmetric: false },
      error: error.message
    }
  }
}

// 计算面部比例（已废弃，保留兼容性）
function calculateFaceProportions(landmarks, box) {
  console.log('⚠️ calculateFaceProportions已废弃，请使用convertGoldenRatioToProportions')
  return convertGoldenRatioToProportions(null)
}

// 计算面部黄金比例 (6个关键点分析)
function calculateGoldenRatio(landmarks, box) {
  try {
    console.log('\n🏛️ ===== 黄金比例计算开始 =====')
    
    const jaw = landmarks.getJawOutline()
    const leftEye = landmarks.getLeftEye()
    const rightEye = landmarks.getRightEye()
    const leftEyebrow = landmarks.getLeftEyeBrow()
    const rightEyebrow = landmarks.getRightEyeBrow()
    const nose = landmarks.getNose()
    const mouth = landmarks.getMouth()
    
    // 计算关键点位置
    const leftEyeCenter = {
      x: leftEye.reduce((sum, p) => sum + p.x, 0) / leftEye.length,
      y: leftEye.reduce((sum, p) => sum + p.y, 0) / leftEye.length
    }
    const rightEyeCenter = {
      x: rightEye.reduce((sum, p) => sum + p.x, 0) / rightEye.length,
      y: rightEye.reduce((sum, p) => sum + p.y, 0) / rightEye.length
    }
    const eyeMidpoint = {
      x: (leftEyeCenter.x + rightEyeCenter.x) / 2,
      y: (leftEyeCenter.y + rightEyeCenter.y) / 2
    }
    
    const mouthCenter = {
      x: mouth.reduce((sum, p) => sum + p.x, 0) / mouth.length,
      y: mouth.reduce((sum, p) => sum + p.y, 0) / mouth.length
    }
    
    const noseBase = nose[3] // 鼻尖
    const noseBridge = nose[0] // 鼻根
    
    // 基础测量
    const faceWidth = Math.abs(jaw[16].x - jaw[0].x)  // 左右脸颊宽度
    
    // 修正脸长计算：应该是从额头到下巴的垂直距离
    // 估算额头位置：通过眉毛位置向上推算
    const foreheadY = Math.min(leftEyebrow[0].y, rightEyebrow[4].y) - (Math.abs(leftEyebrow[0].y - leftEyeCenter.y) * 1.2)
    const chinY = jaw[8].y  // 下巴最低点
    const faceHeight = Math.abs(chinY - foreheadY)  // 真正的脸长：额头到下巴
    
    const eyeWidth = Math.abs(rightEye[3].x - rightEye[0].x)
    const eyeDistance = Math.abs(rightEyeCenter.x - leftEyeCenter.x)
    const mouthWidthBasic = Math.abs(mouth[8].x - mouth[0].x)
    const noseWidth = Math.abs(nose[4].x - nose[0].x)
    
    console.log('📏 基础测量数据:')
    console.log(`   脸宽: ${faceWidth.toFixed(1)}px (左脸颊 ${jaw[0].x.toFixed(1)} 到右脸颊 ${jaw[16].x.toFixed(1)})`)
    console.log(`   脸高: ${faceHeight.toFixed(1)}px (估算额头 ${foreheadY.toFixed(1)} 到下巴 ${chinY.toFixed(1)})`)
    console.log(`   脸长宽比: ${(faceHeight / faceWidth).toFixed(3)} (${faceHeight.toFixed(1)} ÷ ${faceWidth.toFixed(1)})`)
    console.log(`   眼宽: ${eyeWidth.toFixed(1)}px`)
    console.log(`   眼距: ${eyeDistance.toFixed(1)}px`)
    console.log(`   嘴宽: ${mouthWidthBasic.toFixed(1)}px`)
    console.log(`   鼻宽: ${noseWidth.toFixed(1)}px`)
    
    const goldenRatioResults = {}
    let totalScore = 0
    
    // ===== 1. 垂直方向三庭分析 =====
    console.log('\n📐 1. 垂直方向三庭分析 (使用正确的关键点位)')
    
    // 根据用户指导的正确关键点定位
    console.log('\n🎯 正确的关键点定义:')
    console.log(`   nose[0] (眉间点): (${nose[0].x.toFixed(1)}, ${nose[0].y.toFixed(1)})`)
    console.log(`   nose[4] (鼻底点): (${nose[4].x.toFixed(1)}, ${nose[4].y.toFixed(1)})`)
    console.log(`   jaw[8] (下巴底点): (${jaw[8].x.toFixed(1)}, ${jaw[8].y.toFixed(1)})`)
    
    // 1. 眉间点位置 (nose[0])
    const eyebrowCenterY = nose[0].y  // 眉间点就是眉毛中心线
    console.log(`   眉间点Y坐标: ${eyebrowCenterY.toFixed(1)}`)
    
    // 2. 鼻底点位置 (nose[4])  
    const noseBottomY = nose[4].y
    console.log(`   鼻底点Y坐标: ${noseBottomY.toFixed(1)}`)
    
    // 3. 下巴底点位置 (jaw[8])
    const chinBottomY = jaw[8].y
    console.log(`   下巴底点Y坐标: ${chinBottomY.toFixed(1)}`)
    
    // 4. 改进的发际线估算方法
    // 先计算眉间到鼻底和鼻底到下巴底的距离
    const eyebrowToNoseDistance = noseBottomY - eyebrowCenterY  // 眉间到鼻底距离
    const noseToChinDistance = chinBottomY - noseBottomY       // 鼻底到下巴底距离
    
    console.log(`   眉间到鼻底距离: ${eyebrowToNoseDistance.toFixed(1)}px`)
    console.log(`   鼻底到下巴底距离: ${noseToChinDistance.toFixed(1)}px`)
    
    // 发际线到眉间距离 = (眉间到鼻底距离 + 鼻底到下巴底距离) ÷ 2
    const hairlineToEyebrowDistance = (eyebrowToNoseDistance + noseToChinDistance) / 2
    const hairlineY = eyebrowCenterY - hairlineToEyebrowDistance
    
    console.log(`   发际线估算公式: (${eyebrowToNoseDistance.toFixed(1)} + ${noseToChinDistance.toFixed(1)}) ÷ 2 = ${hairlineToEyebrowDistance.toFixed(1)}px`)
    console.log(`   发际线位置: 眉间点 ${eyebrowCenterY.toFixed(1)} - 距离 ${hairlineToEyebrowDistance.toFixed(1)} = ${hairlineY.toFixed(1)}`)
    
    // 基于正确关键点的三庭计算
    console.log('\n📏 基于正确关键点的三庭计算:')
    
    // 上庭：发际线到眉间点 (nose[0])
    const upperCourt = eyebrowCenterY - hairlineY
    // 中庭：眉间点到鼻底点 (nose[0] 到 nose[4])  
    const middleCourt = noseBottomY - eyebrowCenterY
    // 下庭：鼻底点到下巴底点 (nose[4] 到 jaw[8])
    const lowerCourt = chinBottomY - noseBottomY
    
    console.log(`   上庭 (发际线→眉间): ${upperCourt.toFixed(1)}px`)
    console.log(`   中庭 (眉间→鼻底): ${middleCourt.toFixed(1)}px`) 
    console.log(`   下庭 (鼻底→下巴): ${lowerCourt.toFixed(1)}px`)
    
    // 添加关键位置的逻辑验证
    console.log('\n🔬 关键位置逻辑验证:')
    const isLogicalOrder = hairlineY < eyebrowCenterY && eyebrowCenterY < noseBottomY && noseBottomY < chinBottomY
    console.log(`   位置顺序是否正确 (发际线 < 眉间 < 鼻底 < 下巴): ${isLogicalOrder ? '✅ 正确' : '❌ 错误'}`)
    
    if (!isLogicalOrder) {
      console.log('   ⚠️ 位置顺序异常，可能存在关键点定位错误:')
      console.log(`      发际线 ${hairlineY.toFixed(1)} ${hairlineY < eyebrowCenterY ? '<' : '>'} 眉间 ${eyebrowCenterY.toFixed(1)}`)
      console.log(`      眉间 ${eyebrowCenterY.toFixed(1)} ${eyebrowCenterY < noseBottomY ? '<' : '>'} 鼻底 ${noseBottomY.toFixed(1)}`)
      console.log(`      鼻底 ${noseBottomY.toFixed(1)} ${noseBottomY < chinBottomY ? '<' : '>'} 下巴 ${chinBottomY.toFixed(1)}`)
    }
    
    const totalFaceHeight = chinBottomY - hairlineY
    console.log(`   总面高: ${totalFaceHeight.toFixed(1)}px`)
    
    // 检查距离合理性
    const minReasonableDistance = totalFaceHeight * 0.15
    const hasUnreasonableDistance = upperCourt < minReasonableDistance || 
                                   middleCourt < minReasonableDistance || 
                                   lowerCourt < minReasonableDistance
    
    if (hasUnreasonableDistance) {
      console.log(`   ⚠️ 发现异常小的距离（< ${minReasonableDistance.toFixed(1)}px），可能存在定位错误`)
      console.log(`      上庭: ${upperCourt.toFixed(1)}px, 中庭: ${middleCourt.toFixed(1)}px, 下庭: ${lowerCourt.toFixed(1)}px`)
    }
    
    const totalHeight = upperCourt + middleCourt + lowerCourt
    const upperRatio = upperCourt / totalHeight
    const middleRatio = middleCourt / totalHeight
    const lowerRatio = lowerCourt / totalHeight
    
    console.log(`   上庭高度: ${upperCourt.toFixed(1)}px (${(upperRatio * 100).toFixed(1)}%) - 发际线到眉间`)
    console.log(`   中庭高度: ${middleCourt.toFixed(1)}px (${(middleRatio * 100).toFixed(1)}%) - 眉间到鼻底`)
    console.log(`   下庭高度: ${lowerCourt.toFixed(1)}px (${(lowerRatio * 100).toFixed(1)}%) - 鼻底到下巴底`)
    
    // 理想三庭比例：1:1:1 (各33.3%)
    const idealRatio = 1/3
    const upperDeviation = Math.abs(upperRatio - idealRatio)
    const middleDeviation = Math.abs(middleRatio - idealRatio)
    const lowerDeviation = Math.abs(lowerRatio - idealRatio)
    const avgDeviation = (upperDeviation + middleDeviation + lowerDeviation) / 3
    
    // 三庭评分：基于1:1:1理想比例的相似度评分
    // 使用更合理的评分算法：偏差在5%以内得95-100分，10%以内得80-95分，15%以内得60-80分
    let threeCourtScore = 100
    if (avgDeviation <= 0.05) {
      threeCourtScore = 95 + (0.05 - avgDeviation) * 100  // 95-100分
    } else if (avgDeviation <= 0.10) {
      threeCourtScore = 80 + (0.10 - avgDeviation) * 300  // 80-95分
    } else if (avgDeviation <= 0.15) {
      threeCourtScore = 60 + (0.15 - avgDeviation) * 400  // 60-80分
    } else {
      threeCourtScore = Math.max(0, 60 - (avgDeviation - 0.15) * 200)  // 0-60分
    }
    threeCourtScore = Math.max(0, Math.min(100, threeCourtScore))
    
    console.log(`   三庭偏差: 上庭${(upperDeviation * 100).toFixed(1)}%, 中庭${(middleDeviation * 100).toFixed(1)}%, 下庭${(lowerDeviation * 100).toFixed(1)}%`)
    console.log(`   三庭平均偏差: ${(avgDeviation * 100).toFixed(1)}%`)
    console.log(`   三庭得分: ${threeCourtScore.toFixed(1)}/100`)
    
    goldenRatioResults.threeCourts = {
      upperRatio: Math.round(upperRatio * 1000) / 10,
      middleRatio: Math.round(middleRatio * 1000) / 10,
      lowerRatio: Math.round(lowerRatio * 1000) / 10,
      deviation: Math.round(avgDeviation * 1000) / 10,
      score: Math.round(threeCourtScore * 10) / 10,
      analysis: avgDeviation < 0.05 ? '非常接近理想1:1:1比例' : avgDeviation < 0.1 ? '接近理想1:1:1比例' : avgDeviation < 0.15 ? '与理想1:1:1比例有一定差距' : '偏离理想1:1:1比例较多'
    }
    totalScore += threeCourtScore
    
    // ===== 2. 水平方向三眼分析 =====
    console.log('\n👁️ 2. 水平方向三眼分析')
    
    // 验证眼睛数据完整性
    console.log(`🔍 眼睛数据验证:`)
    console.log(`   左眼数据长度: ${leftEye ? leftEye.length : 'null'}`)
    console.log(`   右眼数据长度: ${rightEye ? rightEye.length : 'null'}`)
    
    if (leftEye && leftEye.length >= 6 && rightEye && rightEye.length >= 6) {
      // 68点模型中眼睛点位 (0-based索引):
      // 左眼: 36-41 (数组中为0-5)
      // 右眼: 42-47 (数组中为0-5)
      // leftEye[0] = 左眼外眼角, leftEye[3] = 左眼内眼角
      // rightEye[0] = 右眼内眼角, rightEye[3] = 右眼外眼角
      
      console.log(`\n📍 关键点位坐标验证 (完整数据):`)
      console.log(`   左眼完整坐标:`)
      leftEye.forEach((point, index) => {
        console.log(`     leftEye[${index}]: (${point.x.toFixed(1)}, ${point.y.toFixed(1)})`)
      })
      console.log(`   右眼完整坐标:`)
      rightEye.forEach((point, index) => {
        console.log(`     rightEye[${index}]: (${point.x.toFixed(1)}, ${point.y.toFixed(1)})`)
      })
      
      // 分析点位的X坐标排列，找出真正的内外眼角
      console.log(`\n🔍 点位分析:`)
      const leftEyeXCoords = leftEye.map((p, i) => ({index: i, x: p.x})).sort((a, b) => a.x - b.x)
      const rightEyeXCoords = rightEye.map((p, i) => ({index: i, x: p.x})).sort((a, b) => a.x - b.x)
      
      console.log(`   左眼X坐标排序 (从左到右):`, leftEyeXCoords.map(p => `[${p.index}]:${p.x.toFixed(1)}`).join(', '))
      console.log(`   右眼X坐标排序 (从左到右):`, rightEyeXCoords.map(p => `[${p.index}]:${p.x.toFixed(1)}`).join(', '))
      
      // 根据X坐标确定真正的内外眼角
      const leftEyeOuterCorner = leftEyeXCoords[0]  // 最左边的点
      const leftEyeInnerCorner = leftEyeXCoords[leftEyeXCoords.length - 1]  // 最右边的点
      const rightEyeInnerCorner = rightEyeXCoords[0]  // 最左边的点
      const rightEyeOuterCorner = rightEyeXCoords[rightEyeXCoords.length - 1]  // 最右边的点
      
      console.log(`\n✅ 修正后的关键点:`)
      console.log(`   左眼外眼角: leftEye[${leftEyeOuterCorner.index}] (${leftEyeOuterCorner.x.toFixed(1)}, ${leftEye[leftEyeOuterCorner.index].y.toFixed(1)})`)
      console.log(`   左眼内眼角: leftEye[${leftEyeInnerCorner.index}] (${leftEyeInnerCorner.x.toFixed(1)}, ${leftEye[leftEyeInnerCorner.index].y.toFixed(1)})`)
      console.log(`   右眼内眼角: rightEye[${rightEyeInnerCorner.index}] (${rightEyeInnerCorner.x.toFixed(1)}, ${rightEye[rightEyeInnerCorner.index].y.toFixed(1)})`)
      console.log(`   右眼外眼角: rightEye[${rightEyeOuterCorner.index}] (${rightEyeOuterCorner.x.toFixed(1)}, ${rightEye[rightEyeOuterCorner.index].y.toFixed(1)})`)
      
      // 计算三眼分析 - 使用动态确定的正确点位
      const leftEyeWidthGR = Math.abs(leftEyeInnerCorner.x - leftEyeOuterCorner.x)  // 左眼长度
      const eyeDistanceGR = Math.abs(rightEyeInnerCorner.x - leftEyeInnerCorner.x)  // 眼间距
      const rightEyeWidthGR = Math.abs(rightEyeOuterCorner.x - rightEyeInnerCorner.x)  // 右眼长度
      
      // 同时输出旧方法和新方法的对比
      const leftEyeWidthOld = Math.abs(leftEye[3].x - leftEye[0].x)
      const eyeDistanceOld = Math.abs(rightEye[0].x - leftEye[3].x)
      const rightEyeWidthOld = Math.abs(rightEye[3].x - rightEye[0].x)
      
      console.log(`\n🔄 计算方法对比:`)
      console.log(`   旧方法 - 左眼宽: ${leftEyeWidthOld.toFixed(1)}, 眼距: ${eyeDistanceOld.toFixed(1)}, 右眼宽: ${rightEyeWidthOld.toFixed(1)}`)
      console.log(`   新方法 - 左眼宽: ${leftEyeWidthGR.toFixed(1)}, 眼距: ${eyeDistanceGR.toFixed(1)}, 右眼宽: ${rightEyeWidthGR.toFixed(1)}`)
      
      console.log(`\n📏 三眼测量数据:`)
      console.log(`   左眼宽度(外角到内角): ${leftEyeWidthGR.toFixed(1)}px`)
      console.log(`   双眼间距(内角到内角): ${eyeDistanceGR.toFixed(1)}px`)
      console.log(`   右眼宽度(内角到外角): ${rightEyeWidthGR.toFixed(1)}px`)
      
      // 验证计算逻辑
      console.log(`\n🧮 计算验证:`)
      console.log(`   左眼内眼角X: ${leftEyeInnerCorner.x.toFixed(1)}`)
      console.log(`   右眼内眼角X: ${rightEyeInnerCorner.x.toFixed(1)}`)
      console.log(`   眼间距计算: |${rightEyeInnerCorner.x.toFixed(1)} - ${leftEyeInnerCorner.x.toFixed(1)}| = ${eyeDistanceGR.toFixed(1)}`)
      
      // 理想三眼比例：每部分都应该占总宽度的1/3
      const totalWidthGR = leftEyeWidthGR + eyeDistanceGR + rightEyeWidthGR
      const leftEyeRatioGR = leftEyeWidthGR / totalWidthGR
      const eyeGapRatioGR = eyeDistanceGR / totalWidthGR
      const rightEyeRatioGR = rightEyeWidthGR / totalWidthGR
      
      const leftDeviationGR = Math.abs(leftEyeRatioGR - 1/3)
      const gapDeviationGR = Math.abs(eyeGapRatioGR - 1/3)
      const rightDeviationGR = Math.abs(rightEyeRatioGR - 1/3)
      const threeEyeAvgDeviation = (leftDeviationGR + gapDeviationGR + rightDeviationGR) / 3
      
      const threeEyeScore = Math.max(0, Math.min(100, 100 - (threeEyeAvgDeviation * 300)))
      
      console.log(`\n📊 三眼比例分析结果:`)
      console.log(`   总宽度: ${totalWidthGR.toFixed(1)}px`)
      console.log(`   三眼比例: 左眼${(leftEyeRatioGR*100).toFixed(1)}%, 间距${(eyeGapRatioGR*100).toFixed(1)}%, 右眼${(rightEyeRatioGR*100).toFixed(1)}%`)
      console.log(`   理想比例: 33.3%, 33.3%, 33.3%`)
      console.log(`   三眼偏差: 左眼${leftDeviationGR.toFixed(3)}, 间距${gapDeviationGR.toFixed(3)}, 右眼${rightDeviationGR.toFixed(3)}`)
      console.log(`   三眼平均偏差: ${threeEyeAvgDeviation.toFixed(3)}`)
      console.log(`   三眼得分: ${threeEyeScore.toFixed(1)}/100`)
      
      // 异常检测和优化建议
      if (eyeDistanceGR > leftEyeWidthGR * 1.5 || eyeDistanceGR > rightEyeWidthGR * 1.5) {
        console.log(`⚠️  异常检测: 眼间距(${eyeDistanceGR.toFixed(1)})明显大于眼宽，可能的原因:`)
        console.log(`   1. 面部不是完全正面角度`)
        console.log(`   2. 个体眼间距确实较宽`)
        console.log(`   3. 面部检测精度限制`)
        
        // 尝试使用眼睛中心点计算作为参考
        const leftEyeCenterX = leftEye.reduce((sum, p) => sum + p.x, 0) / leftEye.length
        const rightEyeCenterX = rightEye.reduce((sum, p) => sum + p.x, 0) / rightEye.length
        const eyeDistanceByCenter = Math.abs(rightEyeCenterX - leftEyeCenterX)
        
        console.log(`   替代计算 - 眼中心间距: ${eyeDistanceByCenter.toFixed(1)}px`)
        console.log(`   对比: 内眼角间距${eyeDistanceGR.toFixed(1)} vs 眼中心间距${eyeDistanceByCenter.toFixed(1)}`)
        
        // 如果中心间距更合理，可以考虑使用
        if (Math.abs(eyeDistanceByCenter - (leftEyeWidthGR + rightEyeWidthGR) / 2) < Math.abs(eyeDistanceGR - (leftEyeWidthGR + rightEyeWidthGR) / 2)) {
          console.log(`   💡 建议: 眼中心间距计算更合理，但保持当前算法的一致性`)
        }
      }
      
      console.log(`\n💾 保存三眼分析结果:`)
      console.log(`   leftEyeRatio: ${Math.round(leftEyeRatioGR * 100) / 100}`)
      console.log(`   eyeGapRatio: ${Math.round(eyeGapRatioGR * 100) / 100}`)
      console.log(`   rightEyeRatio: ${Math.round(rightEyeRatioGR * 100) / 100}`)
      console.log(`   前端显示比例: 左眼${(Math.round(leftEyeRatioGR * 100) / 100 * 100).toFixed(1)}%, 眼距${(Math.round(eyeGapRatioGR * 100) / 100 * 100).toFixed(1)}%, 右眼${(Math.round(rightEyeRatioGR * 100) / 100 * 100).toFixed(1)}%`)
      
      goldenRatioResults.threeEyes = {
        leftEyeRatio: Math.round(leftEyeRatioGR * 100) / 100,
        eyeGapRatio: Math.round(eyeGapRatioGR * 100) / 100,
        rightEyeRatio: Math.round(rightEyeRatioGR * 100) / 100,
        deviation: Math.round(threeEyeAvgDeviation * 1000) / 1000,
        score: Math.round(threeEyeScore * 10) / 10,
        analysis: `${threeEyeAvgDeviation < 0.05 ? '完美三眼比例' : threeEyeAvgDeviation < 0.1 ? '优秀三眼比例' : threeEyeAvgDeviation < 0.15 ? '良好三眼比例' : '需要调整'}`
      }
      totalScore += threeEyeScore
    } else {
      console.log('❌ 眼睛数据不完整，跳过三眼分析')
      goldenRatioResults.threeEyes = {
        leftEyeRatio: 0,
        eyeGapRatio: 0,
        rightEyeRatio: 0,
        deviation: 1,
        score: 0,
        analysis: '眼睛数据不完整，无法计算'
      }
      totalScore += 0
    }
    
    // ===== 3. 面部总体比例 (黄金比例1.618) =====
    console.log('\n🏛️ 3. 面部总体比例分析')
    
    // 修正公式：面部总体比例 = 脸长 ÷ 脸宽
    // 注意：这里faceHeight实际上是从下巴到额头的高度（脸长）
    // faceWidth是左右脸颊的宽度（脸宽）
    const faceRatio = faceHeight / faceWidth  // 这个公式是正确的：长÷宽
    const goldenRatio = 1.618
    const goldenRatioDeviation = Math.abs(faceRatio - goldenRatio)
    
    console.log(`   脸长: ${faceHeight.toFixed(1)}px`)
    console.log(`   脸宽: ${faceWidth.toFixed(1)}px`) 
    console.log(`   面部总体比例 (脸长÷脸宽): ${faceRatio.toFixed(3)}`)
    console.log(`   黄金比例标准: ${goldenRatio}`)
    console.log(`   与黄金比例偏差: ${goldenRatioDeviation.toFixed(3)}`)
    
    // 黄金比例评分：偏差越小分数越高，调整评分算法使其更合理
    // 偏差在0.1以内得满分，偏差在0.5以内还能得到较高分数
    const goldenRatioScore = Math.max(0, Math.min(100, 100 - (goldenRatioDeviation * 60)))
    
    console.log(`   黄金比例得分: ${goldenRatioScore.toFixed(1)}/100`)
    
    goldenRatioResults.faceRatio = {
      actualRatio: Math.round(faceRatio * 1000) / 1000,
      goldenRatio: goldenRatio,
      deviation: Math.round(goldenRatioDeviation * 1000) / 1000,
      score: Math.round(goldenRatioScore * 10) / 10,
      analysis: goldenRatioDeviation < 0.15 ? '接近黄金比例' : goldenRatioDeviation < 0.3 ? '较好比例' : '偏离黄金比例',
      formula: '脸长 ÷ 脸宽',
      faceLength: Math.round(faceHeight * 10) / 10,
      faceWidth: Math.round(faceWidth * 10) / 10
    }
    totalScore += goldenRatioScore
    
    // ===== 4. 鼻嘴位置关系黄金比例分析 (基于1.618) =====
    console.log('\n👃 4. 鼻嘴位置关系黄金比例分析 (1.618标准)')
    
    // 精确的关键点定义 (基于68点面部模型)
    const noseRoot = noseBridge   // 鼻根 (nose[0])
    const noseTip = noseBase      // 鼻尖 (nose[3])
    const noseBottom = nose[4]    // 鼻底/鼻小柱底部
    const upperLipSeam = mouth[15] // 上唇缝 (内唇上唇中央点) - 修正为 mouth[15]
    const lowerLip = mouth[17]     // 下唇中央点 (内唇下唇中央点) - 修正为 mouth[17]
    const chinBottom = jaw[8]     // 下巴最低点
    const mouthCornerLeft = mouth[0]   // 嘴角左
    const mouthCornerRight = mouth[8]  // 嘴角右
    
    // 关键距离测量
    const noseBottomToChin = Math.abs(chinBottom.y - noseBottom.y)           // 鼻底到下巴
    const noseBottomToUpperLipSeam = Math.abs(upperLipSeam.y - noseBottom.y) // 鼻底到上唇缝
    const upperLipSeamToChin = Math.abs(chinBottom.y - upperLipSeam.y)       // 上唇缝到下巴
    const lowerLipToChin = Math.abs(chinBottom.y - lowerLip.y)               // 下唇到下巴
    const lipThickness = Math.abs(lowerLip.y - upperLipSeam.y)               // 唇厚 (上唇缝到下唇)
    const mouthWidth = Math.abs(mouthCornerRight.x - mouthCornerLeft.x)      // 嘴宽
    
    console.log(`📏 关键距离测量:`)
    console.log(`   鼻底到下巴: ${noseBottomToChin.toFixed(1)}px`)
    console.log(`   鼻底到上唇缝: ${noseBottomToUpperLipSeam.toFixed(1)}px`)
    console.log(`   上唇缝到下巴: ${upperLipSeamToChin.toFixed(1)}px`)
    console.log(`   下唇到下巴: ${lowerLipToChin.toFixed(1)}px`)
    console.log(`   唇厚 (上唇缝到下唇): ${lipThickness.toFixed(1)}px`)
    console.log(`   嘴宽: ${mouthWidth.toFixed(1)}px`)
    
    // 详细点位诊断信息
    console.log(`\n🔍 关键点位诊断信息:`)
    console.log(`   鼻底 nose[4]: (${noseBottom.x.toFixed(1)}, ${noseBottom.y.toFixed(1)})`)
    console.log(`   上唇缝 mouth[15] (内唇): (${upperLipSeam.x.toFixed(1)}, ${upperLipSeam.y.toFixed(1)})`)
    console.log(`   下唇 mouth[17] (内唇): (${lowerLip.x.toFixed(1)}, ${lowerLip.y.toFixed(1)})`)
    console.log(`   下巴 jaw[8]: (${chinBottom.x.toFixed(1)}, ${chinBottom.y.toFixed(1)})`)
    
    // 测试其他可能的鼻部点位
    console.log(`\n🧪 其他鼻部点位参考:`)
    console.log(`   鼻根 nose[0]: (${nose[0].x.toFixed(1)}, ${nose[0].y.toFixed(1)})`)
    console.log(`   鼻尖 nose[3]: (${nose[3].x.toFixed(1)}, ${nose[3].y.toFixed(1)})`)
    console.log(`   鼻底 nose[4]: (${nose[4].x.toFixed(1)}, ${nose[4].y.toFixed(1)})`)
    console.log(`   左鼻翼 nose[1]: (${nose[1].x.toFixed(1)}, ${nose[1].y.toFixed(1)})`)
    console.log(`   右鼻翼 nose[5]: (${nose[5].x.toFixed(1)}, ${nose[5].y.toFixed(1)})`)
    
    // 测试其他可能的嘴部点位  
    console.log(`\n👄 其他嘴部点位参考:`)
    for (let i = 0; i < mouth.length; i++) {
      console.log(`   mouth[${i}]: (${mouth[i].x.toFixed(1)}, ${mouth[i].y.toFixed(1)})`)
    }
    
    // 按照用户要求的黄金比例公式计算
    // 公式1: (鼻底到下巴) ÷ (鼻底到上唇缝) ≈ 1.618
    const goldenRatio1 = noseBottomToChin / noseBottomToUpperLipSeam
    
    // 公式2: (上唇缝到下巴) ÷ (下唇到下巴) ≈ 1.618  
    const goldenRatio2 = upperLipSeamToChin / lowerLipToChin
    
    // 计算平均值
    const averageGoldenRatio = (goldenRatio1 + goldenRatio2) / 2
    
    console.log(`\n🏛️ 黄金比例计算 (目标值: 1.618):`)
    console.log(`   公式1: (鼻底到下巴) ÷ (鼻底到上唇缝) = ${noseBottomToChin.toFixed(1)} ÷ ${noseBottomToUpperLipSeam.toFixed(1)} = ${goldenRatio1.toFixed(3)}`)
    console.log(`   公式2: (上唇缝到下巴) ÷ (下唇到下巴) = ${upperLipSeamToChin.toFixed(1)} ÷ ${lowerLipToChin.toFixed(1)} = ${goldenRatio2.toFixed(3)}`)
    console.log(`   平均值: (${goldenRatio1.toFixed(3)} + ${goldenRatio2.toFixed(3)}) ÷ 2 = ${averageGoldenRatio.toFixed(3)}`)
    
    // 黄金比例标准值
    const targetGoldenRatio = 1.618
    
    // 计算偏差
    const deviation1 = Math.abs(goldenRatio1 - targetGoldenRatio)
    const deviation2 = Math.abs(goldenRatio2 - targetGoldenRatio)
    const averageDeviation = Math.abs(averageGoldenRatio - targetGoldenRatio)
    
    console.log(`\n📊 偏差分析:`)
    console.log(`   公式1偏差: |${goldenRatio1.toFixed(3)} - ${targetGoldenRatio}| = ${deviation1.toFixed(3)}`)
    console.log(`   公式2偏差: |${goldenRatio2.toFixed(3)} - ${targetGoldenRatio}| = ${deviation2.toFixed(3)}`)
    console.log(`   平均偏差: |${averageGoldenRatio.toFixed(3)} - ${targetGoldenRatio}| = ${averageDeviation.toFixed(3)}`)
    
    // 优化后的评分机制 - 更加宽容和实用
    // 使用分段评分，考虑到实际面部的多样性
    const calculateScore = (deviation) => {
      if (deviation <= 0.05) return 100        // 完美 (偏差 ≤ 0.05)
      else if (deviation <= 0.1) return 95     // 极佳 (偏差 ≤ 0.1)
      else if (deviation <= 0.2) return 85     // 优秀 (偏差 ≤ 0.2)
      else if (deviation <= 0.3) return 75     // 良好 (偏差 ≤ 0.3)
      else if (deviation <= 0.4) return 65     // 中等 (偏差 ≤ 0.4)
      else if (deviation <= 0.5) return 55     // 及格 (偏差 ≤ 0.5)
      else if (deviation <= 0.7) return 45     // 偏差较大
      else if (deviation <= 1.0) return 35     // 偏差很大
      else return Math.max(20, 35 - (deviation - 1.0) * 15) // 最低20分
    }
    
    const score1 = calculateScore(deviation1)
    const score2 = calculateScore(deviation2)
    const averageScore = calculateScore(averageDeviation)
    
    // 综合评分 - 给平均值更高权重，但也考虑单项表现
    const noseMouthScore = (score1 * 0.2 + score2 * 0.3 + averageScore * 0.5)
    
    console.log(`\n🎯 评分结果:`)
    console.log(`   公式1得分: ${score1.toFixed(1)}/100`)
    console.log(`   公式2得分: ${score2.toFixed(1)}/100`)
    console.log(`   平均值得分: ${averageScore.toFixed(1)}/100`)
    console.log(`   综合得分: ${noseMouthScore.toFixed(1)}/100`)
    
    // 优化后的分析结果 - 更加积极和建设性
    let noseMouthAnalysis = '有改善空间'
    if (averageDeviation <= 0.05) noseMouthAnalysis = '完美黄金比例'
    else if (averageDeviation <= 0.1) noseMouthAnalysis = '极佳黄金比例' 
    else if (averageDeviation <= 0.2) noseMouthAnalysis = '优秀黄金比例'
    else if (averageDeviation <= 0.3) noseMouthAnalysis = '良好黄金比例'
    else if (averageDeviation <= 0.4) noseMouthAnalysis = '中等黄金比例'
    else if (averageDeviation <= 0.5) noseMouthAnalysis = '基本协调'
    else if (averageDeviation <= 0.7) noseMouthAnalysis = '略有偏差'
    
    // 给出具体建议
    let suggestions = []
    if (deviation1 > 0.2) {
      if (goldenRatio1 < targetGoldenRatio) {
        suggestions.push('鼻底到上唇缝距离偏长，可考虑缩短人中')
      } else {
        suggestions.push('鼻底到上唇缝距离偏短，整体面中比例需调整')
      }
    }
    if (deviation2 > 0.2) {
      if (goldenRatio2 < targetGoldenRatio) {
        suggestions.push('下唇到下巴距离偏长，可考虑调整下巴轮廓')
      } else {
        suggestions.push('下唇到下巴距离偏短，唇部位置需要调整')
      }
    }
    
    console.log(`\n💡 分析建议:`)
    if (suggestions.length > 0) {
      suggestions.forEach((suggestion, index) => {
        console.log(`   ${index + 1}. ${suggestion}`)
      })
    } else {
      console.log(`   ✨ 鼻嘴比例非常协调，符合黄金比例标准`)
    }
    
    goldenRatioResults.noseMouthRelation = {
      // 主要指标
      actualRatio: Math.round(averageGoldenRatio * 1000) / 1000,
      idealRatio: 1.618,
      deviation: Math.round(averageDeviation * 1000) / 1000,
      score: Math.round(noseMouthScore * 10) / 10,
      analysis: noseMouthAnalysis,
      formula: '[(鼻底到下巴)÷(鼻底到上唇缝) + (上唇缝到下巴)÷(下唇到下巴)] ÷ 2 (使用内唇点位)',
      
      // 详细计算结果
      calculations: {
        ratio1: Math.round(goldenRatio1 * 1000) / 1000,
        ratio2: Math.round(goldenRatio2 * 1000) / 1000,
        average: Math.round(averageGoldenRatio * 1000) / 1000,
        deviation1: Math.round(deviation1 * 1000) / 1000,
        deviation2: Math.round(deviation2 * 1000) / 1000
      },
      
      // 详细测量数据  
      measurements: {
        noseBottomToChin: Math.round(noseBottomToChin * 10) / 10,
        noseBottomToUpperLipSeam: Math.round(noseBottomToUpperLipSeam * 10) / 10,
        upperLipSeamToChin: Math.round(upperLipSeamToChin * 10) / 10,
        lowerLipToChin: Math.round(lowerLipToChin * 10) / 10,
        lipThickness: Math.round(lipThickness * 10) / 10,
        mouthWidth: Math.round(mouthWidth * 10) / 10
      },
      
      // 分项得分
      subscores: {
        formula1: Math.round(score1 * 10) / 10,
        formula2: Math.round(score2 * 10) / 10,
        average: Math.round(averageScore * 10) / 10
      },
      
      // 改善建议
      suggestions: suggestions
    }
    totalScore += noseMouthScore
    
    // ===== 5. 鼻嘴宽度关系分析 (理想1.618) =====
    console.log('\n👃👄 5. 鼻嘴宽度关系分析')
    
    // 检查关键点是否存在
    if (!nose[4] || !nose[8] || !mouth[0] || !mouth[8]) {
      console.log('❌ 关键点缺失，跳过鼻嘴宽度分析')
      console.log(`   鼻子点位: nose[4]=${!!nose[4]}, nose[8]=${!!nose[8]}`)
      console.log(`   嘴巴点位: mouth[0]=${!!mouth[0]}, mouth[8]=${!!mouth[8]}`)
      
      goldenRatioResults.noseMouthWidth = {
        actualRatio: 0,
        idealRatio: 1.618,
        deviation: 1.618,
        score: 0,
        analysis: '关键点缺失，无法计算',
        noseWidth: 0,
        mouthWidth: 0
      }
    } else {
      // 重新定义鼻子宽度：使用鼻翼最宽点
      // 在68点模型中，nose[4]是左鼻翼外侧，nose[8]是右鼻翼外侧
      const noseWidthAccurate = Math.abs(nose[8].x - nose[4].x)  // 鼻翼宽度（鼻翼最宽点）
      const mouthWidthAccurate = Math.abs(mouth[8].x - mouth[0].x) // 嘴角到嘴角的宽度
      
      // 计算鼻嘴宽度比例：嘴宽 ÷ 鼻宽
      const noseMouthWidthRatio = mouthWidthAccurate / noseWidthAccurate
      
      console.log(`   鼻翼宽度: ${noseWidthAccurate.toFixed(1)}px`)
      console.log(`   嘴巴宽度: ${mouthWidthAccurate.toFixed(1)}px`)
      console.log(`   嘴宽/鼻宽比例: ${noseMouthWidthRatio.toFixed(3)}`)
      
      // 理想比例：嘴宽应该是鼻宽的1.618倍（黄金比例）
      const idealNoseMouthRatio = 1.618
      const noseMouthDeviation = Math.abs(noseMouthWidthRatio - idealNoseMouthRatio)
      const noseMouthWidthScore = Math.max(0, Math.min(100, 100 - (noseMouthDeviation * 80)))
      
      console.log(`   理想比例: ${idealNoseMouthRatio}`)
      console.log(`   偏差: ${noseMouthDeviation.toFixed(3)}`)
      console.log(`   鼻嘴宽度得分: ${noseMouthWidthScore.toFixed(1)}/100`)
      
      goldenRatioResults.noseMouthWidth = {
        actualRatio: Math.round(noseMouthWidthRatio * 1000) / 1000,
        idealRatio: idealNoseMouthRatio,
        deviation: Math.round(noseMouthDeviation * 1000) / 1000,
        score: Math.round(noseMouthWidthScore * 10) / 10,
        analysis: noseMouthDeviation < 0.1 ? '完美协调' : noseMouthDeviation < 0.2 ? '良好协调' : noseMouthDeviation < 0.4 ? '基本协调' : '需要调整',
        noseWidth: Math.round(noseWidthAccurate * 10) / 10,
        mouthWidth: Math.round(mouthWidthAccurate * 10) / 10
      }
      totalScore += noseMouthWidthScore
    }
    
    // ===== 6. 眉眼比例分析 =====
    console.log('\n🤨 6. 眉眼比例分析')
    
    // 验证眉毛数据
    console.log(`🔍 眉毛数据验证:`)
    console.log(`   左眉数据长度: ${leftEyebrow ? leftEyebrow.length : 'null'}`)
    console.log(`   右眉数据长度: ${rightEyebrow ? rightEyebrow.length : 'null'}`)
    console.log(`   左眼数据长度: ${leftEye ? leftEye.length : 'null'}`)
    console.log(`   右眼数据长度: ${rightEye ? rightEye.length : 'null'}`)
    
    if (!leftEyebrow || !rightEyebrow || leftEyebrow.length === 0 || rightEyebrow.length === 0) {
      console.log('❌ 眉毛数据不完整，跳过眉眼比例分析')
      goldenRatioResults.eyebrowEyeRatio = {
        actualRatio: 0,
        idealRatio: 2.0,
        deviation: 2.0,
        eyeLength: 0,
        eyebrowDistance: 0,
        symmetry: 0,
        score: 0,
        analysis: '眉毛数据不完整，无法计算'
      }
      totalScore += 0
    } else {
      // 计算眉毛中心点
      const leftEyebrowCenterPoint = {
        x: leftEyebrow.reduce((sum, p) => sum + p.x, 0) / leftEyebrow.length,
        y: leftEyebrow.reduce((sum, p) => sum + p.y, 0) / leftEyebrow.length
      }
      const rightEyebrowCenterPoint = {
        x: rightEyebrow.reduce((sum, p) => sum + p.x, 0) / rightEyebrow.length,
        y: rightEyebrow.reduce((sum, p) => sum + p.y, 0) / rightEyebrow.length
      }
      
      // 计算眉眼间距 (垂直距离) - 修正为眉毛下缘到眼睛上缘
      // 68点模型：眉毛下缘使用眉毛最下方的点，眼睛上缘使用眼睛最上方的点
      const leftEyebrowBottom = Math.max(...leftEyebrow.map(p => p.y))  // 眉毛下缘 (y值最大)
      const rightEyebrowBottom = Math.max(...rightEyebrow.map(p => p.y)) // 眉毛下缘 (y值最大)
      const leftEyeTop = Math.min(...leftEye.map(p => p.y))  // 眼睛上缘 (y值最小)
      const rightEyeTop = Math.min(...rightEye.map(p => p.y)) // 眼睛上缘 (y值最小)
      
      const leftEyebrowEyeDistance = Math.abs(leftEyebrowBottom - leftEyeTop)
      const rightEyebrowEyeDistance = Math.abs(rightEyebrowBottom - rightEyeTop)
      const averageEyebrowEyeDistance = (leftEyebrowEyeDistance + rightEyebrowEyeDistance) / 2
      
      console.log(`\n🔍 眉眼间距详细计算:`)
      console.log(`   左眉毛下缘Y: ${leftEyebrowBottom.toFixed(1)}`)
      console.log(`   左眼睛上缘Y: ${leftEyeTop.toFixed(1)}`)
      console.log(`   左眉眼间距: ${leftEyebrowEyeDistance.toFixed(1)}px`)
      console.log(`   右眉毛下缘Y: ${rightEyebrowBottom.toFixed(1)}`)
      console.log(`   右眼睛上缘Y: ${rightEyeTop.toFixed(1)}`)
      console.log(`   右眉眼间距: ${rightEyebrowEyeDistance.toFixed(1)}px`)
      
      // 计算眼睛长度 (水平长度) - 68点模型标准点位
      // 左眼: leftEye[0]是外眼角, leftEye[3]是内眼角
      // 右眼: rightEye[0]是内眼角, rightEye[3]是外眼角
      const leftEyeLength = Math.abs(leftEye[3].x - leftEye[0].x)  // 左眼外眼角到内眼角
      const rightEyeLength = Math.abs(rightEye[3].x - rightEye[0].x) // 右眼内眼角到外眼角
      const averageEyeLength = (leftEyeLength + rightEyeLength) / 2
      
      console.log(`\n🎯 关键点位验证 (68点面部模型):`)
      console.log(`   左眼外眼角 leftEye[0]: (${leftEye[0].x.toFixed(1)}, ${leftEye[0].y.toFixed(1)})`)
      console.log(`   左眼内眼角 leftEye[3]: (${leftEye[3].x.toFixed(1)}, ${leftEye[3].y.toFixed(1)})`)
      console.log(`   右眼内眼角 rightEye[0]: (${rightEye[0].x.toFixed(1)}, ${rightEye[0].y.toFixed(1)})`)
      console.log(`   右眼外眼角 rightEye[3]: (${rightEye[3].x.toFixed(1)}, ${rightEye[3].y.toFixed(1)})`)
      console.log(`   左眉下缘Y坐标: ${leftEyebrowBottom.toFixed(1)}`)
      console.log(`   右眉下缘Y坐标: ${rightEyebrowBottom.toFixed(1)}`)
      console.log(`   左眼上缘Y坐标: ${leftEyeTop.toFixed(1)}`)
      console.log(`   右眼上缘Y坐标: ${rightEyeTop.toFixed(1)}`)
      
      // 计算眉眼比例：眼睛长度 ÷ 眉眼间距
      const eyeLengthToEyebrowDistanceRatio = averageEyeLength / averageEyebrowEyeDistance
      
      console.log(`\n📏 眉眼比例测量数据:`)
      console.log(`   左眉眼间距: ${leftEyebrowEyeDistance.toFixed(1)}px`)
      console.log(`   右眉眼间距: ${rightEyebrowEyeDistance.toFixed(1)}px`)
      console.log(`   平均眉眼间距: ${averageEyebrowEyeDistance.toFixed(1)}px`)
      console.log(`   左眼长度: ${leftEyeLength.toFixed(1)}px`)
      console.log(`   右眼长度: ${rightEyeLength.toFixed(1)}px`)
      console.log(`   平均眼长度: ${averageEyeLength.toFixed(1)}px`)
      
      // 理想比例：眼睛长度是眉眼间距的2倍
      const idealEyeBrowRatio = 2.0
      console.log(`\n🎯 眉眼比例分析:`)
      console.log(`   实际比例: 眼长 ÷ 眉眼间距 = ${averageEyeLength.toFixed(1)} ÷ ${averageEyebrowEyeDistance.toFixed(1)} = ${eyeLengthToEyebrowDistanceRatio.toFixed(3)}`)
      console.log(`   理想比例: ${idealEyeBrowRatio.toFixed(1)} (眼睛长度是眉眼间距的2倍)`)
      
      // 计算偏差
      const eyeBrowRatioDeviation = Math.abs(eyeLengthToEyebrowDistanceRatio - idealEyeBrowRatio)
      console.log(`   偏差: |${eyeLengthToEyebrowDistanceRatio.toFixed(3)} - ${idealEyeBrowRatio}| = ${eyeBrowRatioDeviation.toFixed(3)}`)
      
      // 眉眼间距对称性分析 - 基于实际眉眼间距
      const eyebrowEyeDistanceSymmetry = Math.abs(leftEyebrowEyeDistance - rightEyebrowEyeDistance)
      const averageEyebrowEyeDistanceForSymmetry = (leftEyebrowEyeDistance + rightEyebrowEyeDistance) / 2
      const eyebrowEyeSymmetryRatio = eyebrowEyeDistanceSymmetry / averageEyebrowEyeDistanceForSymmetry
      const eyebrowSymmetryPercent = (1 - eyebrowEyeSymmetryRatio) * 100
      
      console.log(`\n📐 眉眼间距对称性分析:`)
      console.log(`   左右眉眼间距差值: ${eyebrowEyeDistanceSymmetry.toFixed(1)}px`)
      console.log(`   眉眼间距对称度: ${eyebrowSymmetryPercent.toFixed(1)}%`)
      
      // 评分计算 - 基于美学标准的分级评分
      let ratioScore = 0
      if (eyeBrowRatioDeviation <= 0.1) {
        ratioScore = 100  // 完美比例 (1.9-2.1)
      } else if (eyeBrowRatioDeviation <= 0.2) {
        ratioScore = 90   // 优秀比例 (1.8-1.9, 2.1-2.2)
      } else if (eyeBrowRatioDeviation <= 0.3) {
        ratioScore = 80   // 良好比例 (1.7-1.8, 2.2-2.3)
      } else if (eyeBrowRatioDeviation <= 0.5) {
        ratioScore = 70   // 一般比例 (1.5-1.7, 2.3-2.5)
      } else if (eyeBrowRatioDeviation <= 0.7) {
        ratioScore = 60   // 偏差较大 (1.3-1.5, 2.5-2.7)
      } else {
        ratioScore = Math.max(0, 60 - (eyeBrowRatioDeviation - 0.7) * 50)  // 偏差很大
      }
      
      // 对称性评分：对称度越高分数越高
      const symmetryScore = Math.max(0, Math.min(100, eyebrowSymmetryPercent))
      
      // 综合评分：比例占80%，对称性占20% (比例更重要)
      const eyebrowTotalScore = (ratioScore * 0.8 + symmetryScore * 0.2)
      
      console.log(`\n🎯 眉眼比例评分结果:`)
      console.log(`   比例得分: ${ratioScore.toFixed(1)}/100 (权重80%)`)
      console.log(`   对称得分: ${symmetryScore.toFixed(1)}/100 (权重20%)`)
      console.log(`   综合得分: ${eyebrowTotalScore.toFixed(1)}/100`)
      
      // 分析结果
      let analysis = ''
      if (eyebrowTotalScore >= 90) {
        analysis = '眉眼比例完美'
      } else if (eyebrowTotalScore >= 80) {
        analysis = '眉眼比例优秀'
      } else if (eyebrowTotalScore >= 70) {
        analysis = '眉眼比例良好'
      } else if (eyebrowTotalScore >= 60) {
        analysis = '眉眼比例一般'
      } else {
        analysis = '眉眼比例需要调整'
      }
      
      console.log(`   分析结果: ${analysis}`)
      
      goldenRatioResults.eyebrowEyeRatio = {
        actualRatio: Math.round(eyeLengthToEyebrowDistanceRatio * 1000) / 1000,
        idealRatio: idealEyeBrowRatio,
        deviation: Math.round(eyeBrowRatioDeviation * 1000) / 1000,
        eyeLength: Math.round(averageEyeLength * 10) / 10,
        eyebrowDistance: Math.round(averageEyebrowEyeDistance * 10) / 10,
        symmetry: Math.round(eyebrowSymmetryPercent * 10) / 10,
        score: Math.round(eyebrowTotalScore * 10) / 10,
        analysis: analysis
      }
      totalScore += eyebrowTotalScore
    }
    
    // ===== 最终综合评分 =====
    const finalScore = totalScore / 6 // 6个维度的平均分
    
    console.log('\n🏆 ===== 黄金比例综合评分 =====')
    console.log(`📊 各维度得分:`)
    console.log(`   1. 三庭比例: ${goldenRatioResults.threeCourts.score}/100`)
    console.log(`   2. 三眼比例: ${goldenRatioResults.threeEyes.score}/100`)
    console.log(`   3. 面部总体: ${goldenRatioResults.faceRatio.score}/100`)
    console.log(`   4. 鼻嘴关系: ${goldenRatioResults.noseMouthRelation.score}/100`)
    console.log(`   5. 鼻嘴宽度: ${goldenRatioResults.noseMouthWidth.score}/100`)
    console.log(`   6. 眉眼比例: ${goldenRatioResults.eyebrowEyeRatio.score}/100`)
    console.log(`🎯 综合得分: ${finalScore.toFixed(1)}/100`)
    console.log(`📈 评级: ${finalScore >= 90 ? '完美' : finalScore >= 80 ? '优秀' : finalScore >= 70 ? '良好' : finalScore >= 60 ? '中等' : '需要改善'}`)
    console.log('===========================\n')
    
    // 键名到中文描述的映射
    const dimensionDescriptions = {
      'threeCourts': '三庭比例均衡',
      'threeEyes': '三眼比例协调',
      'faceRatio': '面部总体比例',
      'noseMouthRelation': '鼻嘴位置关系',
      'noseMouthWidth': '鼻嘴宽度比例',
      'eyebrowEyeRatio': '眉眼比例关系'
    }
    
    // 生成优势特征（得分>=80的维度）
    const strengthKeys = Object.keys(goldenRatioResults).filter(key => 
      goldenRatioResults[key] && typeof goldenRatioResults[key].score === 'number' && goldenRatioResults[key].score >= 80
    )
    const strengths = strengthKeys.map(key => dimensionDescriptions[key] || key)
    
    // 生成可优化方面（得分<60的维度）
    const improvementKeys = Object.keys(goldenRatioResults).filter(key => 
      goldenRatioResults[key] && typeof goldenRatioResults[key].score === 'number' && goldenRatioResults[key].score < 60
    )
    const improvements = improvementKeys.map(key => {
      const description = dimensionDescriptions[key] || key
      // 将优势描述转换为改进建议
      if (description.includes('均衡')) return description.replace('均衡', '需要调整')
      if (description.includes('协调')) return description.replace('协调', '需要优化')
      if (description.includes('比例')) return description + '有待改善'
      return description + '需要改善'
    })

    return {
      totalScore: Math.round(finalScore * 10) / 10,
      grade: finalScore >= 90 ? '完美' : finalScore >= 80 ? '优秀' : finalScore >= 70 ? '良好' : finalScore >= 60 ? '中等' : '需要改善',
      details: goldenRatioResults,
      summary: {
        strengths: strengths,
        improvements: improvements
      }
    }
    
  } catch (error) {
    console.error('❌ 黄金比例计算失败:', error)
    return {
      totalScore: 0,
      grade: '计算失败',
      error: error.message,
      details: {}
    }
  }
}

// 生成美化建议
function generateBeautifyRecommendations(landmarks, box, expressions) {
  try {
    const recommendations = []
    
    // 基于面部特征给出建议
    const features = calculateFaceFeatures(landmarks, box)
    const goldenRatioResult = calculateGoldenRatio(landmarks, box)
    const proportions = convertGoldenRatioToProportions(goldenRatioResult)
    
    // 脸型建议
    switch (features.faceShapeEn) {
      case 'round':
        recommendations.push({
          type: 'hairstyle',
          suggestion: '圆脸适合长发或带有层次感的发型，避免齐刘海',
          confidence: 80
        })
        break
      case 'square':
        recommendations.push({
          type: 'hairstyle', 
          suggestion: '方脸适合柔和的卷发或侧分发型，可以柔化脸部线条',
          confidence: 85
        })
        break
      case 'long':
        recommendations.push({
          type: 'hairstyle',
          suggestion: '长脸适合有蓬松感的短发或齐刘海，增加脸部宽度感',
          confidence: 80
        })
        break
      case 'heart':
        recommendations.push({
          type: 'hairstyle',
          suggestion: '心形脸适合中分或有层次的发型，平衡额头宽度',
          confidence: 75
        })
        break
      default:
        recommendations.push({
          type: 'general',
          suggestion: '椭圆脸是最理想的脸型，大部分发型都很适合',
          confidence: 90
        })
    }
    
    // 比例建议
    if (!proportions.threeCourtAnalysis.isBalanced) {
      recommendations.push({
        type: 'makeup',
        suggestion: '可以通过修容技巧调整三庭比例，让面部更加协调',
        confidence: 70
      })
    }
    
    if (!proportions.threeEyeAnalysis.isBalanced) {
      recommendations.push({
        type: 'makeup',
        suggestion: '可以通过眼妆技巧调整三眼比例，让眼部更加协调',
        confidence: 75
      })
    }
    
    // 基于表情给出建议
    const dominantEmotion = Object.keys(expressions).reduce((a, b) => 
      expressions[a] > expressions[b] ? a : b
    )
    
    // 检查悲伤表情（使用英文原始数据进行逻辑判断）
    if (expressions.sad > 0.3) {
      recommendations.push({
        type: 'expression',
        suggestion: '保持微笑可以让面部表情更加亲和，提升整体魅力',
        confidence: 85
      })
    }
    
    // 基于主要表情给出更多建议
    const translatedEmotion = translateExpression(dominantEmotion)
    console.log(`💄 基于表情"${dominantEmotion}"(${translatedEmotion})生成美容建议`)
    
    switch (dominantEmotion.toLowerCase()) {
      case 'neutral':
        recommendations.push({
          type: 'expression',
          suggestion: '可以尝试更多面部表情练习，增加面部表现力',
          confidence: 70
        })
        break
      case 'happy':
        recommendations.push({
          type: 'expression',
          suggestion: '您的笑容很棒！保持这种积极的表情状态',
          confidence: 90
        })
        break
      case 'surprised':
        recommendations.push({
          type: 'expression',
          suggestion: '适度的惊讶表情很有魅力，可以让眼神更加生动',
          confidence: 75
        })
        break
    }
    
    // 默认护肤建议
    recommendations.push({
      type: 'skincare',
      suggestion: '保持良好的护肤习惯，注意防晒和保湿',
      confidence: 90
    })
    
    return recommendations
  } catch (error) {
    console.error('生成美化建议失败:', error)
    return [{
      type: 'general',
      suggestion: '保持自信的笑容是最好的美化方式',
      confidence: 100
    }]
  }
}

// 确保uploads目录存在
const uploadsDir = path.join(__dirname, '../public/uploads')
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true })
}

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadsDir)
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名：时间戳 + 随机数 + 原始扩展名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname))
  }
})

// 文件过滤器，只允许图片
const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image/')) {
    cb(null, true)
  } else {
    cb(new Error('只允许上传图片文件'), false)
  }
}

// 创建multer实例
const upload = multer({ 
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024, // 增加到10MB，因为有些高质量图片可能较大
  }
})

router.get('/getByName',async(req,res)=>{
    try {
        const data = await aiimg.find({name: "魔镜主页展示图"})
        res.json({code:200,data:data})
    } catch (error) {
        res.json({code:500, message: "查询失败", error: error.message})
    }
})

// 通过ID获取图片信息
router.get('/getById', async(req, res) => {
    try {
        const { id } = req.query
        
        if (!id) {
            return res.json({code: 400, message: "缺少图片ID参数"})
        }

        const imageData = await aiimg.findById(id)
        
        if (!imageData) {
            return res.json({code: 404, message: "未找到图片信息"})
        }
        
        // 尝试读取图片文件并转换为base64
        try {
            const imagePath = path.join(__dirname, '../public', imageData.img)
            console.log('尝试读取图片文件:', imagePath)
            
            if (fs.existsSync(imagePath)) {
                const imageBuffer = fs.readFileSync(imagePath)
                const base64Image = imageBuffer.toString('base64')
                const mimeType = imageData.mimeType || 'image/jpeg'
                const base64DataUrl = `data:${mimeType};base64,${base64Image}`
                
                console.log('图片转换为base64成功，大小:', base64Image.length)
                
                res.json({
                    code: 200,
                    data: {
                        ...imageData.toObject(),
                        base64: base64DataUrl,
                        fileExists: true
                    },
                    message: "获取图片信息成功"
                })
            } else {
                console.log('图片文件不存在:', imagePath)
                res.json({
                    code: 200,
                    data: {
                        ...imageData.toObject(),
                        fileExists: false
                    },
                    message: "获取图片信息成功，但图片文件不存在"
                })
            }
        } catch (fileError) {
            console.error('读取图片文件失败:', fileError)
            res.json({
                code: 200,
                data: {
                    ...imageData.toObject(),
                    fileExists: false,
                    fileError: fileError.message
                },
                message: "获取图片信息成功，但无法读取图片文件"
            })
        }
    } catch (error) {
        console.error('获取图片信息失败:', error)
        res.json({code: 500, message: "获取图片信息失败", error: error.message})
    }
})

// 照片上传接口
router.post('/upload', upload.single('photo'), async(req, res) => {
    try {
        if (!req.file) {
            return res.json({code: 400, message: "没有上传文件"})
        }

        // 构建文件访问URL
        const fileUrl = `/uploads/${req.file.filename}`
        
        // 保存到数据库
        const newPhoto = new aiimg({
            img: fileUrl,
            name: req.body.name || "用户上传照片",
            uploadTime: new Date(),
            originalName: req.file.originalname,
            fileSize: req.file.size,
            mimeType: req.file.mimetype
        })

        const savedPhoto = await newPhoto.save()
        
        res.json({
            code: 200,
            message: "照片上传成功",
            data: {
                id: savedPhoto._id,
                url: fileUrl,
                name: savedPhoto.name,
                uploadTime: savedPhoto.uploadTime
            }
        })
    } catch (error) {
        console.error('照片上传失败:', error)
        res.json({code: 500, message: "照片上传失败", error: error.message})
    }
})

// 获取用户上传的照片列表
router.get('/getUserPhotos', async(req, res) => {
    try {
        const photos = await aiimg.find({
            name: { $regex: "用户上传照片|魔镜测脸" }
        }).sort({ uploadTime: -1 })
        
        res.json({
            code: 200,
            data: photos,
            message: "获取照片列表成功"
        })
    } catch (error) {
        res.json({code: 500, message: "获取照片列表失败", error: error.message})
    }
})

// 面部分析接口
router.post('/analyzeFace', upload.single('photo'), async(req, res) => {
    try {
        // 检查系统是否准备就绪
        if (!isSystemReady()) {
            return res.json({
                code: 503,
                message: "AI系统正在初始化中，请稍后重试",
                data: {
                    modelLoaded: isModelLoaded
                }
            })
        }

        if (!req.file) {
            return res.json({code: 400, message: "没有上传文件"})
        }

        console.log('🔍 开始分析图片:', req.file.filename)
        
        // 构建文件路径
        const imagePath = path.join(__dirname, '../public/uploads', req.file.filename)
        const fileUrl = `/uploads/${req.file.filename}`
        
        // 加载图片进行分析
        const img = await loadImage(imagePath)
        const canvas = createCanvas(img.width, img.height)
        const ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0)
        
        if (!faceapi.nets.ageGenderNet.isLoaded) {
            console.log('⚠️ 警告: ageGenderNet模型未加载')
        }
        
        const detections = await faceapi
            .detectAllFaces(canvas, new faceapi.TinyFaceDetectorOptions())
            .withFaceLandmarks()
            .withFaceExpressions()
            .withAgeAndGender()  // 添加年龄性别检测
            

        if (detections.length === 0) {
            return res.json({
                code: 200,
                message: "未检测到人脸",
                data: {
                    success: false,
                    faceCount: 0,
                    faces: [],
                    imageInfo: {
                        width: img.width,
                        height: img.height,
                        path: imagePath
                    }
                }
            })
        }

        // 处理检测结果
        const analysisResults = detections.map((detection, index) => {
            const box = detection.detection.box
            const landmarks = detection.landmarks
            const expressions = detection.expressions
            const age = detection.age
            const gender = detection.gender
            const genderProbability = detection.genderProbability
            

            // 分析表情
            const emotionScores = {}
            const emotionScoresTranslated = {}
            let dominantEmotion = ''
            let dominantEmotionTranslated = ''
            let maxScore = 0

            Object.keys(expressions).forEach(emotion => {
                const score = Math.round(expressions[emotion] * 100)
                emotionScores[emotion] = score
                emotionScoresTranslated[translateExpression(emotion)] = score
                
                if (expressions[emotion] > maxScore) {
                    maxScore = expressions[emotion]
                    dominantEmotion = emotion
                    dominantEmotionTranslated = translateExpression(emotion)
                }
            })


            // 分析性别和年龄（简化日志）
            
            // 根据gender的实际格式处理数据
            let genderResult = null
            if (gender) {
                if (typeof gender === 'string') {
                    const prob = typeof genderProbability === 'number' ? Math.round(genderProbability * 100) : 0
                    genderResult = {
                        gender: gender, // 保留英文枚举
                        genderZh: gender === 'male' ? '男性' : (gender === 'female' ? '女性' : '未知'),
                        probability: prob
                    }
                } else if (typeof gender === 'object' && gender.gender && gender.probability !== undefined) {
                    genderResult = {
                        gender: gender.gender,
                        genderZh: gender.gender === 'male' ? '男性' : (gender.gender === 'female' ? '女性' : '未知'),
                        probability: Math.round(gender.probability * 100)
                    }
                } else {
                    genderResult = {
                        gender: 'unknown',
                        genderZh: '未知',
                        probability: 0,
                        note: '无法解析性别数据'
                    }
                }
            }

            const ageResult = age ? {
                age: Math.round(age),
                ageRange: getAgeRange(age)
            } : null

            return {
                faceIndex: index + 1,
                boundingBox: {
                    x: Math.round(box.x),
                    y: Math.round(box.y),
                    width: Math.round(box.width),
                    height: Math.round(box.height)
                },
                confidence: Math.round(detection.detection.score * 100) / 100,
                // 性别和年龄信息
                gender: genderResult,
                age: ageResult,
                landmarks: {
                    jaw: landmarks.getJawOutline().map(p => ({ x: Math.round(p.x), y: Math.round(p.y) })),
                    leftEyebrow: landmarks.getLeftEyeBrow().map(p => ({ x: Math.round(p.x), y: Math.round(p.y) })),
                    rightEyebrow: landmarks.getRightEyeBrow().map(p => ({ x: Math.round(p.x), y: Math.round(p.y) })),
                    leftEye: landmarks.getLeftEye().map(p => ({ x: Math.round(p.x), y: Math.round(p.y) })),
                    rightEye: landmarks.getRightEye().map(p => ({ x: Math.round(p.x), y: Math.round(p.y) })),
                    nose: landmarks.getNose().map(p => ({ x: Math.round(p.x), y: Math.round(p.y) })),
                    mouth: landmarks.getMouth().map(p => ({ x: Math.round(p.x), y: Math.round(p.y) }))
                },
                expressions: {
                    dominant: dominantEmotionTranslated, // 使用翻译后的中文表情
                    dominantOriginal: dominantEmotion, // 保留原始英文表情作为备用
                    confidence: Math.round(maxScore * 100),
                    scores: emotionScoresTranslated, // 使用翻译后的中文表情分数
                    scoresOriginal: emotionScores // 保留原始英文表情分数作为备用
                },
                features: calculateFaceFeatures(landmarks, box),
                // 计算黄金比例和基础比例
                ...(() => {
                    const goldenRatio = calculateGoldenRatio(landmarks, box)
                    const proportions = convertGoldenRatioToProportions(goldenRatio)
                    return {
                        goldenRatio: goldenRatio,
                        proportions: proportions
                    }
                })(),
                beautifyRecommendations: generateBeautifyRecommendations(landmarks, box, expressions)
            }
        })

        // 保存分析结果到数据库
        const photoData = {
            img: fileUrl,
            name: req.body.name || "AI面部分析",
            uploadTime: new Date(),
            originalName: req.file.originalname,
            fileSize: req.file.size,
            mimeType: req.file.mimetype,
            faceAnalysis: {
                success: true,
                faceCount: detections.length,
                faces: analysisResults,
                timestamp: new Date().toISOString()
            }
        }

        const newPhoto = new aiimg(photoData)
        const savedPhoto = await newPhoto.save()

        // 输出分析结果摘要
        console.log('📊 分析结果:')
        analysisResults.forEach((result, index) => {
            console.log(`  人脸${index + 1}: ${result.features?.faceShape || '未知脸型'}, ${result.gender?.genderZh || '未知性别'}, ${result.age?.ageRange || '未知年龄'}, 主要表情: ${result.expressions?.dominant || '未知'}`)
            if (result.goldenRatio) {
                console.log(`    黄金比例得分: ${result.goldenRatio.totalScore || 0}/100 (${result.goldenRatio.grade || '未评级'})`)
            }
        })

        // 调用Ollama AI进行深度分析
        let aiAnalysisResult = null
        try {
            
            const aiAnalysisData = {
                faceCount: detections.length,
                faces: analysisResults,
                imageInfo: {
                    width: img.width,
                    height: img.height,
                    path: imagePath
                }
            }
            
            // 同步调用AI分析以获取结果
            aiAnalysisResult = await analyzeWithOllama(aiAnalysisData)
            
        } catch (aiError) {
            console.error('⚠️ AI分析调用出错:', aiError.message)
            aiAnalysisResult = null
        }


        // 翻译分析结果为中文
        const translatedAnalysisResults = translateObjectTexts(analysisResults)
        let translatedAiAnalysis = translateAnalysisText(aiAnalysisResult)
        
            // 对AI分析结果进行额外的英文检测和清理
            if (translatedAiAnalysis && typeof translatedAiAnalysis === 'string') {
                // 检测是否还有英文内容
                const englishMatches = translatedAiAnalysis.match(/[a-zA-Z]+/g);
                if (englishMatches && englishMatches.length > 0) {
                
                // 最后一轮强制翻译
                let finalText = translatedAiAnalysis;
                
                // 替换常见的未翻译词汇
                const finalTranslations = {
                    'ratio': '比例',
                    'analysis': '分析', 
                    'recommendation': '建议',
                    'score': '得分',
                    'percentage': '百分比',
                    'percent': '百分比',
                    'width': '宽度',
                    'height': '高度',
                    'length': '长度',
                    'shape': '形状',
                    'size': '尺寸',
                    'feature': '特征',
                    'measurement': '测量',
                    'calculation': '计算',
                    'result': '结果',
                    'value': '数值',
                    'data': '数据',
                    'point': '点',
                    'line': '线',
                    'curve': '曲线',
                    'angle': '角度',
                    'distance': '距离',
                    // 性别相关词汇
                    'gentlemen': '先生',
                    'gentleman': '先生',
                    'lady': '女士',
                    'ladies': '女士们',
                    'man': '男性',
                    'woman': '女性',
                    'men': '男性',
                    'women': '女性',
                    'male': '男性',
                    'female': '女性',
                    'masculine': '阳刚',
                    'feminine': '柔美',
                    'handsome': '英俊',
                    'beautiful': '美丽',
                    // 医美建议相关
                    'slimmer': '更纤细',
                    'slim': '纤细',
                    'enhance': '增强',
                    'improve': '改善',
                    'optimization': '优化',
                    'optimize': '优化',
                    'adjust': '调整',
                    'balance': '平衡',
                    'harmonize': '协调',
                    'contour': '轮廓',
                    'highlight': '突出',
                    'define': '定义',
                    'refine': '精细化',
                    'modification': '修改',
                    'enhancement': '增强',
                    'improvement': '改善',
                    'adjustment': '调整',
                    // 常见形容词
                    'better': '更好',
                    'worse': '更差',
                    'larger': '更大',
                    'smaller': '更小',
                    'bigger': '更大',
                    'thicker': '更厚',
                    'thinner': '更薄',
                    'wider': '更宽',
                    'narrower': '更窄',
                    'longer': '更长',
                    'shorter': '更短',
                    'higher': '更高',
                    'lower': '更低',
                    'strong': '强',
                    'weak': '弱',
                    'sharp': '尖锐',
                    'soft': '柔和',
                    'round': '圆润',
                    'angular': '棱角分明',
                    'smooth': '平滑',
                    'rough': '粗糙',
                    'clear': '清晰',
                    'blurred': '模糊',
                    'defined': '轮廓清晰',
                    'prominent': '突出',
                    // 医学术语
                    'facial': '面部',
                    'cosmetic': '美容',
                    'aesthetic': '美学',
                    'symmetrical': '对称',
                    'asymmetrical': '不对称',
                    'proportional': '比例协调',
                    'harmonious': '和谐',
                    'balanced': '平衡',
                    'unbalanced': '不平衡',
                    'natural': '自然',
                    'artificial': '人工',
                    'perfect': '完美',
                    'ideal': '理想',
                    'excellent': '优秀',
                    'good': '良好',
                    'average': '一般',
                    'poor': '较差',
                    // 脸型相关
                    'oval': '椭圆形',
                    'round': '圆形',
                    'square': '方形',
                    'heart': '心形',
                    'oblong': '长形',
                    'diamond': '菱形',
                    'triangular': '三角形',
                    // 五官相关
                    'eyes': '眼睛',
                    'eyebrows': '眉毛',
                    'nose': '鼻子',
                    'mouth': '嘴巴',
                    'lips': '嘴唇',
                    'chin': '下巴',
                    'cheeks': '脸颊',
                    'forehead': '额头',
                    'jawline': '下颌线',
                    'cheekbones': '颧骨',
                    // 小标题翻译
                    'face contouring': '面部轮廓塑形',
                    'eye shape adjustment': '眼型调整',
                    'nose and mouth optimization': '鼻唇优化',
                    'hairstyle suggestion': '发型建议',
                    'makeup suggestions': '化妆建议',
                    'skincare advice': '护肤建议',
                    'age-specific suggestions': '年龄定制建议',
                    'gender-specific suggestions': '性别定制建议',
                    'key data analysis': '关键数据分析',
                    'professional opinion': '专业意见',
                    // 其他常见词汇
                    'overall': '整体',
                    'general': '总体',
                    'specific': '具体',
                    'detailed': '详细',
                    'comprehensive': '全面',
                    'thorough': '彻底',
                    'effective': '有效',
                    'suitable': '合适',
                    'appropriate': '适当',
                    'recommended': '推荐',
                    'suggested': '建议',
                    'advised': '建议',
                    'consider': '考虑',
                    'try': '尝试',
                    'avoid': '避免',
                    'maintain': '保持',
                    'focus': '重点关注',
                    'attention': '注意'
                };
                
                for (const [en, zh] of Object.entries(finalTranslations)) {
                    const regex = new RegExp(`\\b${en}\\b`, 'gi');
                    finalText = finalText.replace(regex, zh);
                }
                
                // 如果还有英文，记录警告并进行最后处理
                const remainingEnglish = finalText.match(/[a-zA-Z]+/g);
                if (remainingEnglish && remainingEnglish.length > 0) {
                    // 最后的英文清理：移除或替换任何剩余的英文词汇
                    let cleanedText = finalText;
                    remainingEnglish.forEach(englishWord => {
                        if (englishWord.length <= 2) {
                            cleanedText = cleanedText.replace(new RegExp(`\\b${englishWord}\\b`, 'gi'), '');
                        } else if (englishWord.toLowerCase() === 'the' || englishWord.toLowerCase() === 'and' || englishWord.toLowerCase() === 'or') {
                            cleanedText = cleanedText.replace(new RegExp(`\\b${englishWord}\\b`, 'gi'), '');
                        } else {
                            cleanedText = cleanedText.replace(new RegExp(`\\b${englishWord}\\b`, 'gi'), '相关特征');
                        }
                    });
                    
                    cleanedText = cleanedText.replace(/\s+/g, ' ').replace(/[,，]\s*[,，]/g, '，').trim();
                    finalText = cleanedText;
                }
                
                translatedAiAnalysis = finalText;
            }
        }
        
        console.log('✅ 面部分析完成')

        res.json({
            code: 200,
            message: "面部分析完成",
            data: {
                id: savedPhoto._id,
                url: fileUrl,
                name: savedPhoto.name,
                uploadTime: savedPhoto.uploadTime,
                analysis: {
                    success: true,
                    faceCount: detections.length,
                    imageInfo: {
                        width: img.width,
                        height: img.height,
                        path: imagePath
                    },
                    faces: translatedAnalysisResults,
                    aiAnalysis: translatedAiAnalysis, // 使用翻译后的AI分析结果
                    timestamp: new Date().toISOString()
                }
            }
        })

    } catch (error) {
        console.error('❌ 面部分析失败:', error)
        res.json({
            code: 500,
            message: "面部分析失败",
            error: error.message
        })
    }
})

// 系统状态检查接口
router.get('/status', (req, res) => {
    res.json({
        code: 200,
        message: "系统状态",
        data: {
            modelLoaded: isModelLoaded,
            systemReady: isSystemReady(),
            sampleCount: global.faceShapeStats.count,
            timestamp: new Date().toISOString()
        }
    })
})

// 脸型统计分析接口
router.get('/faceShapeStats', (req, res) => {
    try {
        if (global.faceShapeStats.samples.length === 0) {
            return res.json({
                code: 200,
                message: "暂无统计数据",
                data: {
                    sampleCount: 0,
                    distribution: {},
                    averages: {}
                }
            })
        }
        
        analyzeFaceShapeDistribution()
        
        const samples = global.faceShapeStats.samples
        const shapeCount = {}
        const ratioStats = {
            faceRatio: [],
            jawRatio: [],
            cheekRatio: [],
            foreheadRatio: []
        }
        
        samples.forEach(sample => {
            shapeCount[sample.result] = (shapeCount[sample.result] || 0) + 1
            ratioStats.faceRatio.push(sample.faceRatio)
            ratioStats.jawRatio.push(sample.jawRatio)
            ratioStats.cheekRatio.push(sample.cheekRatio)
            ratioStats.foreheadRatio.push(sample.foreheadRatio)
        })
        
        const avgFaceRatio = ratioStats.faceRatio.reduce((a, b) => a + b, 0) / ratioStats.faceRatio.length
        const avgJawRatio = ratioStats.jawRatio.reduce((a, b) => a + b, 0) / ratioStats.jawRatio.length
        const avgCheekRatio = ratioStats.cheekRatio.reduce((a, b) => a + b, 0) / ratioStats.cheekRatio.length
        const avgForeheadRatio = ratioStats.foreheadRatio.reduce((a, b) => a + b, 0) / ratioStats.foreheadRatio.length
        
        res.json({
            code: 200,
            message: "脸型统计数据",
            data: {
                sampleCount: samples.length,
                distribution: shapeCount,
                averages: {
                    faceRatio: parseFloat(avgFaceRatio.toFixed(3)),
                    jawRatio: parseFloat(avgJawRatio.toFixed(3)),
                    cheekRatio: parseFloat(avgCheekRatio.toFixed(3)),
                    foreheadRatio: parseFloat(avgForeheadRatio.toFixed(3))
                },
                suggestions: {
                    roundFaceThreshold: Math.max(0.85, avgFaceRatio - 0.15),
                    roundJawThreshold: Math.min(0.90, avgJawRatio + 0.05),
                    roundCheekThreshold: Math.min(0.85, avgCheekRatio + 0.05)
                },
                samples: samples.slice(-10) // 最近10个样本
            }
        })
    } catch (error) {
        res.json({code: 500, message: "获取统计数据失败", error: error.message})
    }
})

module.exports = router;

